When the input binary tree is {3,9,20,#,#,15,7}, why does my code return an output of 2 instead of 3?


  • 0
    J
    public class Solution {
        public int maxDepth(TreeNode root) {
            int left = 0;
            int right = 0;
            
            if(root == null){
                return 0;
            }else if(root.left != null){
                left = maxDepth(root.left);
            }else if(root.right != null){
                right = maxDepth(root.right);
            }
            
            return Math.max(1+left, 1+right); 
        }
    }

  • 2
    M
     if(root == null){
         return 0;
     }else if(root.left != null){
         left = maxDepth(root.left);
     }else if(root.right != null){
         right = maxDepth(root.right);
    

    If root.left is not null, the condition is true, so the next else if is not checked. Therefore, the root.right is never expanded, and remains at zero. Instead of using else if, just use if for all three conditions.


  • 0
    J

    wow thanks for pointing that out :)


  • 0
    M

    Actually, you have if(root == null) return 0, so you don't even need the other conditions at all. If they are null, then it will return zero, which is the same result as skipping the call.


  • 0
    J

    truuu May I know how I could possibly get to your level in programming?


  • 0
    M

    For me, years of practice and writing code for fun. I suggest playing around with code and seeing what doing different things does. I actually spent several years grading programming assignments, and that helped a lot, seeing 40-50 different attempts at solving the same problem and trying to figure out why certain ones worked and others didn't.


Log in to reply
 

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