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).
//traverse + divided conquer
public class Solution {
/**
* @param root the root of binary tree
* @return the length of the longest consecutive sequence path
*/
private int longest = 0;
public int longestConsecutive(TreeNode root) {
helper(root);
return longest;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int sub = 1;
int left = helper(root.left);
int right = helper(root.right);
if (root.left != null && root.val + 1 == root.left.val) {
sub = Math.max(sub, left + 1);
}
if (root.right != null && root.val + 1 == root.right.val) {
sub = Math.max(sub, right + 1);
}
if (longest < sub) {
longest = sub;
}
return sub;
}
}