111. Minimum Depth of Binary Tree

Total Accepted: 93588
Total Submissions: 309967
Difficulty: Easy

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.

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null)return 0;
        Queue<TreeNode> comeIn=new LinkedList<TreeNode>();
        int res=0;
        comeIn.offer(root);
        while(!comeIn.isEmpty()){
            int size=comeIn.size();
            res++;
            for(int i = 0;i < size; ++ i){
                TreeNode tmp=comeIn.poll();
                if(tmp.left == null && tmp.right == null)
                    return res;
                if(tmp.left != null)
                    comeIn.offer(tmp.left);
                if(tmp.right != null)
                    comeIn.offer(tmp.right);    
            }
        }
        return 520;
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。