1 题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示
节点总数 <= 10000
2 解题思路
2.1 方法1:DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int maxDepth(TreeNode root) {
dfs(root,0);
return max;
}
private void dfs(TreeNode node, int depth) {
if (node == null) {
if (max < depth) max = depth;
return;
}
dfs(node.left,depth + 1);
dfs(node.right,depth + 1);
}
}
2.2 方法2:DFS
树的深度等于左子树的深度与右子树的深度中的最大值+1。
算法流程:
- 终止条件:当root为空,说明已越过叶节点,因此返回深度0。
- 递推工作:本质上是对树做后序遍历。
- 计算节点root的左子树的深度,即调用maxDepth(root.left);
- 计算节点root的右子树的深度,即调用maxDepth(root.right);
- 返回值:返回此树的深度,即max(maxDepth(root.left),maxDepth(root.right))+1;
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
复杂度分析:
- 时间复杂度O(N):N为树的节点数量,计算树的深度需要遍历所有节点。
- 空间复杂度O(N):最差情况下(当树退化为链表时),递归深度可达到N。
2.3 方法3:BFS
- 树的层序遍历 / 广度优先搜索往往利用队列实现。
- 关键点:每遍历一层,则计数器+1,直到遍历完成,则可得到树的深度。
算法流程:
- 特例处理:当root为空,直接返回深度0;
- 初始化:队列queue(加入根节点root),计数器res=0。
- 循环遍历:当queue为空时跳出。
- 初始化一个空列表tmp,用于临时存储下一层节点;
- 遍历队列:遍历queue中的各个节点node,并将其左子节点和右子节点加入tmp;
- 更新队列:执行queue=tmp,将下一层节点赋值给queue;
- 统计层数:执行res+=1,代表层数加1;
- 返回值:返回res即可。
/**
* 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;
List<TreeNode> tmp;
List<TreeNode> queue = new LinkedList<>();
queue.add(root);
int res = 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;
res++;
}
return res;
}
}
复杂度分析:
- 时间复杂度O(N):N为树的节点数量,计算树的深度需要遍历所有节点。
- 空间复杂度O(N):最差情况下(当树平衡时),队列 queue 同时存储N/2个节点。