Please take a look at it if you are a java expert , thanks a lot


  • 2
    F
    public int maxDepth(TreeNode root) {
      if(root == null) return 0;
    //   int left = maxDepth(root.left);
    //   int right = maxDepth(root.right);
    //   return left > right ? left + 1 : right + 1;
      return  maxDepth(root.left) > maxDepth(root.right)? maxDepth(root.left) + 1 :  maxDepth(root.right) + 1;
    }
    

    The problem is that when I try to run the code above, I got time exceed error. But if I use the code that I comment, then it works. What is the problem??


  • 8
    S

    Not a java expert myself but your problem is language independent: By writing everything in a single line, you called both maxDepth(root.left) and maxDepth(root.right) twice, thus doubling the time it needs.


  • 0
    F

    Thank you so much!


  • 0
    M

    If you want to keep it on one line, use

    return Math.max(maxDepth(root.left), maxDepth(root.right))+1;

Log in to reply
 

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