zoukankan      html  css  js  c++  java
  • 298. Binary Tree Longest Consecutive Sequence

    package LeetCode_298
    
    /**
     * 298. Binary Tree Longest Consecutive Sequence (Locked by leetcode)
     * https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence/description
     * Given a binary tree, find the length of the longest consecutive sequence path.
    The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-childconnections.
    The longest consecutive path need to be from parent to child (cannot be the reverse).
    
    Example 1:
    Input:
    1
    
    3
    / 
    2  4
    
    5
    Output: 3
    Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
     * */
    
    class TreeNode(var `val`: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }
    
    class Solution {
        var result = 0
        fun longestConsecutive(root: TreeNode?): Int {
            if (root == null) {
                return 0
            }
            dfs(root, 0, 0)
            return result
        }
    
        /*
       每个遍历到的节点,看节点值是否比参数值(父节点值)大1(因为cannot be the reverse),如果是则长度加1,否则长度重置为1,
       然后更新结果 res,再遍历左右子节点
       */
        private fun dfs(root: TreeNode?, value: Int, current_: Int) {
            if (root == null) {
                return
            }
            var currentLen = current_
            if (root.`val` == value + 1) {
                currentLen++
            } else {
                currentLen = 1
            }
            result = Math.max(currentLen, result)
    
            dfs(root.left, root.`val`, currentLen)
            dfs(root.right, root.`val`, currentLen)
        }
    }
  • 相关阅读:
    第六次作业SSM
    第五次作业——MVC2项目实践
    第四次作业——JSP显示新闻
    第三次作业——servlet应用
    第二次作业——模仿登录页面
    第一次作业——Java web基础
    Alpha项目测试
    作业三
    第二次作业
    第一次阅读作业-201731062609-庞斌
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12861070.html
Copyright © 2011-2022 走看看