[LintCode] Problem 595 - Binary Tree Longest Consecutive Sequence

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).

Example

No.1

Input:

1
2
3
4
5
6
7
1
\
3
/ \
2 4
\
5

Output:3

Explanation:
Longest consecutive sequence path is 3-4-5, so return 3.

No.2

Input:

1
2
3
4
5
6
7
  2
\
3
/
2
/
1

Output:2

Explanation:
Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

Code

1
2
3
4
5
6
7
8
public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private int max = 0;

public int longestConsecutive(TreeNode root) {
dfs(root, null, 0);
return max;
}

private void dfs(TreeNode root, TreeNode parent, int count) {
if (root == null)
return;

count = (parent == null) || (root.val - parent.val == 1) ? count + 1 : 1;
max = Math.max(max, count);

dfs(root.left, root, count);
dfs(root.right, root, count);
}