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
2
3
4
5
6
7
1
\
3
/ \
24
\
5
Longest consecutive sequence path is 3-4-5, so return 3.
1
2
3
4
5
6
7
2
\
3
/
2
/
1
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
Traverse
这种方式主要是用一个全局变量来记录max.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int max = 1;
publicintlongestConsecutive(TreeNode root){
if (root == null)
return0;
helper(root);
return max;
}
// return the length of the longest consecutive sequence including the root