[LintCode] Minimum Depth of Binary Tree

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.

Example

Given a binary tree as follow:

        1

     /     \ 

   2       3

          /    \

        4      5  

The minimum depth is 2

 

SOLUTION:

最小深度这个题其实跟level order traversal是一个思路,不过要用一个level纪录层数,然后不需要纪录每一层的点信息,注意就是level++的操作要在每一层开始的时候操作,也就是从新计算queue的size的时候做这个事情,然后初始化level是0。

代码如下:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int minDepth(TreeNode root) {
        int level = 0;
        if (root == null){
            return 0;
        }
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        while (!q.isEmpty()){
            int size = q.size();
            level++;
            for (int i = 0; i < size; i++){
                TreeNode node = q.poll();
                if (node.left == null && node.right ==null){
                    return level;
                }
                if (node.left != null){
                    q.offer(node.left);
                }
                if (node.right != null){
                    q.offer(node.right);
                }
                // level++;
            }
        }
        return level;
    }
}
View Code

 

 

posted @ 2015-11-04 23:22  Tri_tri_tri  阅读(105)  评论(0)    收藏  举报