Two recursive ways in Java with explanation


  • 0
    L

    The question clearly mentions it is the number of nodes. It means that a null node (i.e. a child of leaf) can return a 0 depth. Keeping track of max is simple: just check the size of left and right subtrees and pick the max in each stack. Here is the code for that:

       public int maxDepth(TreeNode root) {
            return helper(root,0);
        }
        
        private int helper(TreeNode root, int d) {
            if(root==null) {
                return 0;
            }
            
            return 1+ Math.max(helper(root.left,d+1),
                helper(root.right,d+1));
        }
      
    

    Another way is use a global variable and keep track of the max in the null node, i.e. when you encounter a null node, you have visited a child of a leaf. Refresh your max at that point of time and you should be okay. Here is the code:

        private int max=0;
        public int maxDepth(TreeNode root) {
            helper(root,0);
            return max;
        }
        
        private void helper(TreeNode root, int depth) {
           if(root==null) {
               max = Math.max(max,depth);
               return;
           } 
           
           helper(root.left,depth+1);
           helper(root.right,depth+1);
        } 
    

Log in to reply
 

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