One line java solution


  • 11
    R
    public class Solution {
        public int maxDepth(TreeNode root) {
            
            return (root == null)?0:Math.max(1+maxDepth(root.left),1+maxDepth(root.right));
        }
    }

  • -3
    W
    public class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null)return 0;
        if(root.left==null&&root.right == null)return 1;
        return maxDepth(root.left)>maxDepth(root.right)?maxDepth(root.left)+1:maxDepth(root.right)+1;
    }
    

    My solution is similar to you ,but why you do not get Time Limitted?


  • 0
    Y

    In your return statement, you do maxDepth twice for each node(twice for root.left and twirce for root.right), which is very expensive.


  • 0
    P

    maxDepth must be called twice, if you check the one line solution, it is also called twice.


  • 0
    Y

    You can check again to see if it is twice for each node or twice in total.


  • 0
    P

    see ur point. Thanks


  • 3
    Y
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        int maxdepth=Math.max(maxDepth(root.left),maxDepth(root.right))+1;
        return maxdepth;
    }
    

    Mine is similar to yours, but yours is more concise!


Log in to reply
 

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