easy to understand Java Solution using level-order traversal


  • 0
    S
    public class Solution {
        public int minDepth(TreeNode root) {
            if(root==null)return 0;
            int level = 1;
            Queue<TreeNode> q = new LinkedList<TreeNode>();
          
            q.add(root);        
            while(!q.isEmpty()){          
                int levelSize = q.size();
       
                for(int i=0; i<levelSize; i++){
                    TreeNode n = q.poll();
                    if(n.left==null && n.right==null) return minDepth;
                    if(n.left!=null)q.add(n.left);
                    if(n.right!=null)q.add(n.right);
                }//all nodes in the current level will be visited in this for-loop, and if we find any leaf node, we just return the current level, which is the shortest distance from the leaf to the root.
                level++; // Done with current level, didn't find any leaf node, now proceed to next level
            }
            
            return level;
        }
    }
    

Log in to reply
 

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