本文正在参与掘金团队号上线活动,点击 查看大厂春招职位
一、题目描述:
这个题目说的是,给你一棵二叉树,你要找到从根节点到最近的叶子节点的深度。
比如说,给你的二叉树是:
1
/ \
2 4
/ \
8 16
这棵树有 3 个叶子节点,分别是 2,8,16。
最近的叶子节点是 2,根节点到 2 共有两个节点,因此最小深度是 2。
再比如说,给你的二叉树是:
1
\
2
\
4
这棵树唯一的叶子节点是 4,根节点到它共有 3 个节点,因此最小深度是 3。
二、思路分析:
这道题考察的树的遍历。
因为存在最左(右)子树的情况,所以不能像上题(二叉树最大深度)直接比较。 需要比较左右子树。
思路:
- 递归遍历 (
DFS) - 用队列模拟 层级遍历 (
BFS)
三、AC 代码:
public class LeetCode_111 {
// Time: o(n) Space: o(n) faster: 100%
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null) return 1;
if (root.left != null && root.right != null) {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
if (root.left != null) return minDepth(root.left) + 1;
return minDepth(root.right) + 1;
}
// Time: o(n) Space: o(n), Faster: 80.09%
public int minDepthWith(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; ++i) {
TreeNode node = queue.poll();
if (node.left == null && node.right == null) return depth;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
++depth;
}
return -1;
}
}
四、总结:
树的遍历模板
树的遍历有四种:
- 前序遍历
- 中序遍历
- 后序遍历
- 层级遍历
这里也可以分为:深度优先遍历(DFS) 和 广度优先遍历 (BFS)
层级遍历:是为广度优先遍历。
其他遍历:是为深度优先遍历。
1. 前序遍历
void traverse(TreeNode root) {
if (null == root) return;
// 前序遍历的代码
traverse(root.left);
traverse(root.right);
}
2. 中序遍历
void traverse(TreeNode root) {
if (null == root) return;
traverse(root.left);
// 前序遍历的代码
traverse(root.right);
}
3. 后序遍历
void traverse(TreeNode root) {
if (null == root) return;
traverse(root.left);
traverse(root.right);
// 前序遍历的代码
}
4. 层级遍历
用队列模拟
void traverse(TreeNode root) {
if (null == root) return;
// 初始化队列,将 root 加入队列
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode cur = q.poll();
// 层级遍历代码
System.out.println(root.val);
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
}