Tuesday, October 16, 2012

[LeetCode] Minimum depth of Binary Tree

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

解题思路:典型的BSF. 用一个Queue就好了

Java code:

public int minDepth(TreeNode root) {
        Queue tmp = new LinkedList ();      
        if(root == null) return 0;   
        
        tmp.add(root);
        int minDepth = 0;
        
        while(!tmp.isEmpty()){
            int count = tmp.size();
            minDepth++;
            
            for(int i = 0; i < count; i++){
               TreeNode t = tmp.poll();
               
               if(t.left == null && t.right == null){
                   return minDepth;
               }else{
                   if(t.left != null) tmp.add(t.left);
                   if(t.right != null) tmp.add(t.right);           
               }
            }
            
        }
        return minDepth; 
    }

No comments:

Post a Comment