zoukankan      html  css  js  c++  java
  • 二叉树的最小深度

    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 }

     举一反三,获取最大深度也可以用这种方式,当节点的左子树和右子树都为null的时候 不处理即可

  • 相关阅读:
    SecureCRT的设置和美化
    strtod-strtod, 字符串 转 数字 函数
    Debug : array type has incomplete element type
    Linux上Core Dump文件的形成和分析
    centos7,进程最大打开文件数 too many open files错误
    不使用临时变量交换两个值
    C语言的设计理念
    K&R C vs ANSI C(数据类型提升)
    再也不怕C语言的声明了
    K&R C vs ANSI C(数据类型转换)
  • 原文地址:https://www.cnblogs.com/lilefordream/p/7079976.html
Copyright © 2011-2022 走看看