111. 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.

这道题我用的BFS做,要求根到叶节点最短深度,我首先就想到了BFS并分层遍历。只要找到第一个叶节点就停止搜索返回已经搜索的层次就可以。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null){
            return 0;
        }        
        Queue queue = new LinkedList<>();
        queue.offer(root);
        int level = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            level++;
            for (int i = 0; i < size; i++){
                TreeNode curt = queue.poll();
                if (curt.left == null && curt.right == null){
                    return level;        
                }
                if (curt.left != null){
                    queue.offer(curt.left);
                }
                if (curt.right != null){
                    queue.offer(curt.right);
                } 
            }
        }
        return level;
    }
}

你可能感兴趣的:(111. Minimum Depth of Binary Tree)