问:本题和 104. 二叉树的最大深度 的区别是什么?为什么本题代码要更复杂一些?
答:对于非叶节点,把握一个共同原则:如果一个儿子是空节点,另一个儿子不是空节点,那么答案只能来自非空的那一侧。
求最大深度,空节点返回 0,直接计算 max,一定会取到有节点的那一侧(因为深度比 0 大)。
求最小深度,空节点返回 0,直接计算 min,会取到空节点,不符合「答案只能来自非空的那一侧」。所以求最小深度必须多写一些逻辑。
Python
参考:灵茶山艾府
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
elif not root.left and not root.right: # 这个判断分支不加也可以,其他分支可覆盖
return 1
elif not root.right:
return 1 + self.minDepth(root.left)
elif not root.left:
return 1 + self.minDepth(root.right)
else:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
Java
法1:BFS
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int depth = 1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int curSize = queue.size();
for (int i = 0; i < curSize; ++i) { // 上面记录curSize配合内部for循环的操作很棒!!!
TreeNode topNode = queue.poll();
if (topNode.left == null && topNode.right == null) {
return depth;
}
if (topNode.left != null) {
queue.offer(topNode.left);
}
if (topNode.right != null) {
queue.offer(topNode.right);
}
}
++depth;
}
return depth;
}
}
法2:DFS
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
} else if (root.left == null) {
return 1 + minDepth(root.right);
} else if (root.right == null) {
return 1 + minDepth(root.left);
} else {
return Math.min(1 + minDepth(root.left), 1 + minDepth(root.right));
}
}
}
文章介绍了两种方法:BFS(广度优先搜索)和DFS(深度优先搜索),用于求解给定二叉树中从根节点到最浅叶子节点的最小深度。BFS采用队列实现,DFS则使用递归策略。
246

被折叠的 条评论
为什么被折叠?



