Simple Java solution with recursion

  • 0

    Pay attention that you need to count at a leaf only. If only the right or the left child is missing -- you don't send the recursion there. Here is the code :

      public int minDepth(TreeNode root) {
            if(root==null) {
                return 0;
            return helper(root,0);
        private int helper(TreeNode root,int d) {
            if(root == null) {
                return Integer.MAX_VALUE;
            if(root.left==null && root.right==null) { //leaf node.
                return 1;
            int min = Math.min(helper(root.left,d+1),helper(root.right,d+1));
            return min==Integer.MAX_VALUE?Integer.MAX_VALUE:1+min; 

Log in to reply

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