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

LC.298.Binary Tree Longest Consecutive Sequence

时间:2018-03-01 11:38:14      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:time   pat   sum   path sum   longest   ref   start   pac   ++   

https://leetcode.com/problems/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-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.
PATH 还是从头走到能走的, 不是从半路 开始走
如果 不满足条件 把当前的MAX = 1
HELPER 函数想到了,全局变量想到了,helper 和 主函数的关系这块儿还需要多做题
time: o(n) space: o(n)
 1  int res =0;
 2     public int longestConsecutive(TreeNode root) {
 3         if (root == null) return res;
 4         helper(root,0,root.val);
 5         return res ;
 6     }
 7 
 8     private void helper(TreeNode root, int max, int target) {
 9         //corner case
10         if (root == null) return ;
11         if (root.val == target){
12             max++;
13         } else{
14             max = 1 ;
15         }
16         //这里很巧妙的随时更新 RES 这样就不需要HELPER 函数弄返回值
17         res = Math.max(res, max) ;
18         //细节: MAX 这里是 INT 不是 REF 所以不需要像PATH SUM II 里面 最后一步要 REMOVE
19        //换句话说,如果 Max= 2  先走LEFT, left只是对它那一层的 Max 进行改变,
20         // 沿着左边走到最后 跳出后,走RIGHT 时,MAX 还是 2!!!
21         helper(root.left,max, root.val+1);
22         helper(root.right,max, root.val+1);
23     }

 




LC.298.Binary Tree Longest Consecutive Sequence

标签:time   pat   sum   path sum   longest   ref   start   pac   ++   

原文地址:https://www.cnblogs.com/davidnyc/p/8487147.html

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