My simple java solution


  • 0
    X
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        private int minDepth=Integer.MAX_VALUE;
        
        public int minDepth(TreeNode root) {
            if(root==null) return 0;
            root.val=1;
            Search(root);
            return minDepth;
        }
        
        //val is the cost from root to this node
        public void Search(TreeNode root){
            if(root==null) return;
            
            //terminate the search if this path is obviously not the shortest
            if(root.val>=minDepth) return;
            
            //find a leaf, update minDepth if needed
            if(root.left==null&&root.right==null){  
                minDepth=Math.min(root.val,minDepth);
            }
            
            if(root.left!=null){
                root.left.val=root.val+1;
                Search(root.left);
            }
           
            if(root.right!=null){
                 root.right.val=root.val+1;
                 Search(root.right);
            } 
        }
    }

Log in to reply
 

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