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

104.Maximum Depth of Binary Tree

时间:2017-09-17 22:06:10      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:hid   ide   logs   左右   代码   二叉树的高度   tail   poll   link   

题目链接https://leetcode.com/submissions/detail/119156148/

题目大意:返回一个二叉树的高度。

法一:深搜,左右子树直接递归(耗时1ms),代码如下:

技术分享
1     private static int maxDepth(TreeNode root) {
2         if(root == null) {
3             return 0;
4         }
5         int leftDepth = maxDepth(root.left);
6         int rightDepth = maxDepth(root.right);
7         return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
8     }
View Code

法二:广搜,层序遍历,注意记录每层的结点个数,以记录当前层是否遍历完(耗时3ms),代码如下:

技术分享
 1     private static int maxDepth1(TreeNode root) {
 2         if(root == null) {
 3             return 0;
 4         }
 5         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 6         queue.offer(root);
 7         int depth = 0;
 8         int width = 1;
 9         while(!queue.isEmpty()) {
10             TreeNode node = queue.poll();
11             width--;
12             if(node.left != null) {
13                 queue.offer(node.left);
14             }
15             if(node.right != null) {
16                 queue.offer(node.right);
17             }
18             if(width == 0) {
19                 depth++;
20                 width = queue.size();
21             }
22         }
23         return depth;
24     }
View Code

 

104.Maximum Depth of Binary Tree

标签:hid   ide   logs   左右   代码   二叉树的高度   tail   poll   link   

原文地址:http://www.cnblogs.com/cing/p/7537761.html

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