echo

任生命穿梭 时间的角落

0%

二叉树的最大深度

104. 二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回它的最大深度 3 。

方法一:递归

当前树的最大深度为左右子树的最大深度加一,左右子树又以同样的方式进行计算。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
//根节点为空,返回 0
if(root == null){
return 0;
}
//只有根节点,返回 1
if(root.left == null && root.right == null){
return 1;
}
//返回左右子树最大深度加一
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}

时间复杂度O(n),树中的每个结点被访问一次。

空间复杂度O(h),h 为树的高度。

方法二:层次遍历

我们可以使用层次遍历来计算二叉树的深度。

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
29
30
31
32
33
34
35
36
37
38
39
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
//队列中保存下一层的结点
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int ans = 0;
while(!queue.isEmpty()){
//获得当前层数结点的个数
int size = queue.size();
//将当前层每一个结点的子节点入队
while(size > 0){
TreeNode t = queue.poll();
if(t.left != null){
queue.offer(t.left);
}
if(t.right != null){
queue.offer(t.right);
}
//当前层结点数减一
--size;
}
//二叉树层数加一
++ans;
}
return ans;
}
}

时间复杂度O(n),空间复杂度最坏O(n)。