• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

posted @ 2014-05-04 22:32  neverlandly  阅读(302)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3