码迷,mamicode.com
首页 > 其他好文 > 详细

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.

时间:2019-06-08 15:11:15      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:evel   return   nim   dep   size   import   res   def   min   

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public int run(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> s  = new LinkedList<TreeNode>();
        s.add(root);
        int start = 0;
        int end = 1;
        int level = 1;
        while(s!=null){
            TreeNode node = s.poll();
            start++;
            if(node.left == null && node.right == null){
                return level;
            }
            if(node.left!=null){
                s.add(node.left);
            }
            if(node.right!=null){
                s.add(node.right);
            }
            if(start == end){
                start = 0;
                level++;
                end = s.size();
            }
        }
        return level;
    }
}

 

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.

标签:evel   return   nim   dep   size   import   res   def   min   

原文地址:https://www.cnblogs.com/q-1993/p/10990601.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!