104.Maximum Depth of Binary Tree

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

 

posted on 2017-09-17 21:00  二十年后20  阅读(111)  评论(0)    收藏  举报

导航