My code is ugly, but i think it's right. I cant pass the 52th test case.

Please help me.

public int longestConsecutive(TreeNode root) {

if(root == null){

return 0;

}

if(root.left == null && root.right == null){

return 1;

}

return helper(root);

}

public int helper(TreeNode root){

if(root.left == null && root.right == null){

return 0;

}

int left = 0, right = 0;

if(root.left != null){

int temp = longestConsecutive(root.left);

if(root.left.val == root.val + 1){

left = 1 + (temp == 0 ? 1 : temp);

}else{

left = temp;

}

}

if(root.right != null){

int temp = longestConsecutive(root.right);

if(root.right.val == root.val + 1){

right = 1 + (temp == 0 ? 1 : temp);

}else{

right = temp;

}

}

return Math.max(left, right);

}