What's wrong with my code? Help


  • 0

    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);
    }


  • 0
    L

    Try this simple example, you will know why your solution is wrong.

    [1,2,null,3,null,0,null,1]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.