Binary Tree Longest Consecutive Sequence07/26
Last updated
Last updated
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
public int longestConsecutive(TreeNode root) {
// write your code here
int res = helper(root,null,0);
return res;
}
public int helper(TreeNode root,TreeNode parent, int l){
if(root == null){
return 0;
}
int length = (parent != null && parent.val+1 == root.val) ? l+1: 1;
int leftLength = helper(root.left,root,length);
int rightLength = helper(root.right,root,length);
return Math.max(length,Math.max(leftLength,rightLength));
}
}