leetcode104.二叉树的最大深度

leetcode104.二叉树的最大深度

二月 23, 2020

leetcode 104. 二叉树的最大深度


给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
    / \
  15 7
返回它的最大深度 3 。

方法一:递归

感觉有点理解二叉树的题了,都往递归上去靠,无非就是四种遍历方式(前序,中序,后序,层序)。比较两个子树,哪一个更深。

1
2
3
4
5
6
public int maxDepth(TreeNode root) {
if(root==null)return 0;
int depth=1;
depth+=Math.max(maxDepth(root.left),maxDepth(root.right));
return depth;
}

方法二:迭代

这个是在评论区看见的,开始想这么做,但是想了一会没想出来,于是去走捷径了。preCount相当于记录着这一层的节点有多少个,每次出队列都减一,同时进队列的再用pCount计数,是下一层的节点有多少个。bfs的方法,很有意思。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int preCount = 1;
int pCount = 0;
int level = 0;
while (!q.isEmpty()) {
TreeNode temp = q.poll();
preCount--;
if (temp.left != null) {
q.offer(temp.left);
pCount++;
}
if (temp.right != null) {
q.offer(temp.right);
pCount++;
}
if (preCount == 0) {
preCount = pCount;
pCount = 0;
level++;
}
}
return level;
}

leetcode 27/100