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

LinCode 刷题 之二叉树最小深度

时间:2017-06-26 13:38:25      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:返回   min   offer   null   blog   nod   amp   tree   http   

http://www.lintcode.com/zh-cn/problem/minimum-depth-of-binary-tree/  题目描述信息

 

二叉树的结构定义如下:

/**
 * 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;
 *     }
 * }
 */

 

 

给出一棵如下的二叉树:

        1

     /     \ 

   2       3

          /    \

        4      5  

这个二叉树的最小深度为 2

 

   思路 层级访问儿二叉树某个节点的左子树和右子数都没有 就是最小深度,广度优先遍历二叉树即可(队列)

 1 public class Solution {
 2     /**
 3      * @param root: The root of binary tree.
 4      * @return: An integer.
 5      */
 6     public int minDepth(TreeNode root) {
 7        Queue<TreeNode> queue=new LinkedList<TreeNode>();
 8     
 9         int num;
10         if(root==null){
11             num=0;
12         }else{
13             num=1;
14             queue.add(root);
15         }
16         while(!queue.isEmpty()){
17             int size = queue.size();
18             //遍历本层级的所有元素
19             for(int i=0;i<size;i++){
20                 TreeNode node = queue.poll();
21                 if(node.left==null&&node.right==null){
22                     queue=new LinkedList<>();//找到最深节点返回
23                    return num;
24                 }else{
25                     if(node.left!=null){
26                         queue.offer(node.left);
27                     }
28                     
29                     if(node.right!=null){
30                         queue.offer(node.right);
31                     }
32                 }
33             }
34             //层级+1
35             num++;
36             
37         }
38         
39         return num;
40     }
41 }

 

LinCode 刷题 之二叉树最小深度

标签:返回   min   offer   null   blog   nod   amp   tree   http   

原文地址:http://www.cnblogs.com/lilefordream/p/7079976.html

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