首页 > 其他 > 详细

298. Binary Tree Longest Consecutive Sequence

时间:2020-05-10 00:00:57      阅读:71      评论:0      收藏:0      [点我收藏+]
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)
    }
}

 

298. Binary Tree Longest Consecutive Sequence

原文:https://www.cnblogs.com/johnnyzhao/p/12861070.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!