1ms java ez understanding solution with constant and assistant method (optimized)


  • 0
    H
    public class Solution {
        //store the temp min depth
        int minDeepth = Integer.MAX_VALUE;
        public int minDepth(TreeNode root) {
            if(root==null){
                return 0;
            }else {
                minDeepth(root,0);
                return minDeepth;
            }
        }
        
        
        
        public void minDeepth(TreeNode node,int lastDepth){
            if(lastDepth<minDeepth){
                if(node.left==null&&node.right==null){
                    minDeepth = lastDepth+1;
                }else {
                    if(node.left!=null&&node.right==null){
                        minDeepth(node.left,lastDepth+1);
                    }else if(node.right!=null&&node.left==null){
                        minDeepth(node.right,lastDepth+1);
                    }else {
                         minDeepth(node.left,lastDepth+1);
                         minDeepth(node.right,lastDepth+1);
                    }
                }
            }
        }
    }
    

    compare to solution like blow

        public static int minDepth(TreeNode root) {
           if (root == null) return 0; 
           if (root.left == null) return minDepth(root.right) + 1;
           if (root.right == null) return minDepth(root.left) + 1; 
           return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
     }
    

    my solution is far more efficient。


  • 0
    H
    This post is deleted!

  • 0
    B

    You are no longer doing a Breadth First Search, you are doing a Depth First Search, which is not at all the best approach for this kind of problem.


Log in to reply
 

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