码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Binary Tree Longest Consecutive Sequence

时间:2018-05-23 11:57:56      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:art   return   最大的   ++   start   nec   int   max   star   

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-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).

For example,

   1
         3
    /    2   4
                 5 
Longest consecutive sequence path is 3-4-5, so return 3.

   2
         3
    / 
   2    
  / 
 1 
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.

 

Recursion:

时间O(n) 空间O(h)

因为要找最长的连续路径,我们在遍历树的时候需要两个信息,一是目前连起来的路径有多长,二是目前路径的上一个节点的值。我们通过递归把这些信息代入,然后通过返回值返回一个最大的就行了。

    public int longestConsecutive(TreeNode root) {
        if(root == null){
            return 0;
        }
        return findLongestConsecutivePath(root, 0, root.val-1);
    }
    
    public int findLongestConsecutivePath(TreeNode root, int length, int preVal){
        if(root == null){
            return 0;
        }
        if(preVal == root.val - 1){
            length++;
        }
        else{
            length = 1;
        }
        return Math.max(length, Math.max(findLongestConsecutivePath(root.left, length, root.val),findLongestConsecutivePath(root.right, length, root.val)));
    }

 

LeetCode - Binary Tree Longest Consecutive Sequence

标签:art   return   最大的   ++   start   nec   int   max   star   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/9075907.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!