recursive solution in Java with the use of a helper method


  • 0
    R
    class Solution {
        public int minDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            return helper(root, 1);
        }
        private int helper(TreeNode root, int depth){
    
            if(root.left != null && root.right != null){
                return Math.min(helper(root.left,depth + 1), helper(root.right,depth+1));
            }
            else if(root.left != null){
                return helper(root.left, depth+1);
            }
            else if(root.right != null){
                return helper(root.right, depth+1);
            }
            else{
                return depth;
            }
        }
    }
    

Log in to reply
 

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