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 }
  • 相关阅读:
    表单高级和表格高级
    XHTML基础知识
    浅析JavaScript访问对象属性和方法及区别
    互联网盈利模式研习笔记之二:佣金与分成
    互联网盈利模式研习笔记之一:流量变现
    前端两年开发经验需要了解的常识!
    拖拽原理
    js中常见兼容性
    前端性能优化
    JS框架常识。
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3708113.html
Copyright © 2011-2022 走看看