首页 > 其他 > 详细

104.Maximum Depth of Binary Tree

时间:2017-09-17 21:24:29      阅读:272      评论:0      收藏:0      [点我收藏+]

题目链接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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!