题目:
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.
解答:
分治,一种不带返回值,但需要用全局变量,一种带返回值,不用全局变量:
1.
//有全局变量
private int max = 0;
public void Helper(TreeNode root, int target, int count) {
if (root == null) return;
if (root.val == target) {
count++;
} else {
count = 1;
}
max = Math.max(max, count);
Helper(root.left, root.val + 1, count);
Helper(root.right, root.val + 1, count);
}
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
Helper(root, root.val + 1, 1);
return max;
}
2.
public int Helper(TreeNode root, int target, int count) {
if (root == null) return 1;
count = root.val == target ? count + 1 : 1;
int left = Helper(root.left, root.val + 1, count);
int right = Helper(root.right, root.val + 1, count);
return Math.max(Math.max(left, right), count);
}
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
return Math.max(Helper(root.left, root.val + 1, 1), Helper(root.right, root.val + 1, 1));
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。