public class Solution {
public int longestConsecutive(TreeNode root) {
//You can code here
if(root==null)
return 0;
int count=1;
return Math.max(longestConsecutiveHelper(root.left,count),longestConsecutiveHelper(root.right,count));
}
public int longestConsecutiveHelper(TreeNode node, int count){
if(node==null)
return count;
int leftCount=0;
int rightCount=0;
if(node.left==null && node.right==null)
{
return count;
}
if(node.left!=null)
{
if(node.left.val-node.val==1)
{
leftCount=longestConsecutiveHelper(node.left,count+1);
}
}
if(node.right!=null)
{
if(node.right.val-node.val==1)
{
rightCount=longestConsecutiveHelper(node.right,count+1);
}
}
return Math.max(leftCount+1,rightCount+1);
}
}
Editor is loading...