zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    这道题因为不仔细的缘故两次过,与Maximum Depth of Binary Tree问题类似,区别在于这个问题中,如果一个节点左子树为空、右子树有值,则该节点的深度应取决于右子树,而不能直接取min{左,右}

    Recursive: 

    1 public int minDepth(TreeNode root) {
    2     if(root == null)
    3         return 0;
    4     if(root.left == null)
    5         return minDepth(root.right)+1;
    6     if(root.right == null)
    7         return minDepth(root.left)+1;
    8     return Math.min(minDepth(root.left),minDepth(root.right))+1;
    9 }

    Iterative:

     1 public int minDepth(TreeNode root) {
     2     if(root == null)
     3         return 0;
     4     LinkedList queue = new LinkedList();
     5     int curNum = 0;
     6     int lastNum = 1;
     7     int level = 1;
     8     queue.offer(root);
     9     while(!queue.isEmpty())
    10     {
    11         TreeNode cur = queue.poll();
    12         if(cur.left==null && cur.right==null)
    13             return level;
    14         lastNum--;
    15         if(cur.left!=null)
    16         {
    17             queue.offer(cur.left);
    18             curNum++;
    19         }
    20         if(cur.right!=null)
    21         {
    22             queue.offer(cur.right);
    23             curNum++;
    24         }
    25         if(lastNum==0)
    26         {
    27             lastNum = curNum;
    28             curNum = 0;
    29             level++;
    30         }
    31     }
    32     return 0;
    33 }
  • 相关阅读:
    我很高兴,很欣慰:)
    任天堂Wii低价发布 游戏革命今冬开始
    血狮——当年号称已经超越C&C的游戏
    网络游戏《防沉迷系统开发标准(试行)》内容
    经典劣作《大卡车》演示视频
    SANTENDO的大脑训练计划
    linq
    对象构造者
    扩展方法
    隐式类型化本地变量
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3708113.html
Copyright © 2011-2022 走看看