题目:

题解:
1、先序遍历
解题思路:加入一个计数器,进行先序遍历。
复杂度分析:
- 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。
- 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution {
int count = 0;
int max = 0;
public int maxDepth(TreeNode root) {
dfs(root);
return max;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
count++;
if (count > max) {
max = count;
}
dfs(root.left);
dfs(root.right);
count--;
}
}
2、后序遍历
解题思路:此树的深度和其左(右)子树的深度之间的关系。显然,此树的深度 等于 左子树的深度 与 右子树的深度 中的 最大值 +1。
复杂度分析:
- 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。
- 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。
代码:
1
2
3
4
5
6class Solution2 {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
3、广度优先遍历
解题思路:每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。
复杂度分析:
- 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。
- 空间复杂度 O(N) : 最差情况下(当树平衡时),队列
queue同时存储 N/2 个节点。
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution3 {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
List<TreeNode> queue = new LinkedList<TreeNode>() {{ add(root);}};
List<TreeNode> tmp;
int count = 0;
while (!queue.isEmpty()) {
tmp = new LinkedList<>();
for (TreeNode node: queue) {
if (node.left != null) tmp.add(node.left);
if (node.right != null) tmp.add(node.right);
}
queue = tmp;
count++;
}
return count;
}
}
