题目
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
解题思路
解法一:后序遍历(DFS)
树的深度等于“左子树的深度”与“右子树的深度”中的最大值再加上本层节点深度,因此可采用后序遍历的方式计算树的深度。
算法步骤:
- 1)终止条件:当 root 为空,说明已越过叶节点,因此返回深度为 0 。
- 2)递推步骤:
- 2.1)计算节点 root 的左子树的深度 left = maxDepth(root.left);
- 2.2)计算节点 root 的右子树的深度 right = maxDepth(root.right);
- 3)返回值:返回此节点的深度,即 max(left, right) + 1。
复杂度分析:
时间复杂度:O(N)。N 为树的节点数量,计算树的深度需要遍历所有节点。
空间复杂度:O(N)。最差情况下(当树退化为链表时),递归深度可达到 N。
解法二:层序遍历(BFS)
计算树的深度也可采用层次遍历的方式,而树的层序遍历(BFS)往往利用队列实现。 每遍历一层,深度 +1,直到遍历完成,则可得到树的深度。
算法步骤:
- 1)特例处理: 当 root 为空,直接返回深度为 0。
- 2)初始化: 队列 queue (加入根节点 root ),计数器 level = 0。
- 3)当 queue 不为空时循环遍历队列:
- 3.1)计算本层节点数对应的队列长度;
- 3.2)遍历 queue 中的本层节点 ,并将其左子节点和右子节点加入队列;
- 3.3)本层节点遍历完后,执行 level++ ,代表层数加 1;
- 4)返回值: 返回 level 即可。
复杂度分析:
时间复杂度:O(N)。N 为树的节点数量,计算树的深度需要遍历所有节点。
空间复杂度:O(N)。最差情况下(当树平衡时),队列 queue 同时存储 N/2 个节点。
代码
解法一:(后序遍历)DFS
/**
* 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;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
解法二:(层次遍历)BFS
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int level = 0;
while(!queue.isEmpty()){
int n = queue.size();
for(int i=0; i<n; i++){
TreeNode cur = queue.poll();
if(cur.left != null){
queue.offer(cur.left);
}
if(cur.right != null){
queue.offer(cur.right);
}
}
level++;
}
return level;
}
}