LeetCode 题解工作台
删除给定值的叶子节点
给你一棵以 root 为根的二叉树和一个整数 target ,请你删除所有值为 target 的 叶子节点 。 注意,一旦删除值为 target 的叶子节点,它的父节点就可能变成叶子节点;如果新叶子节点的值恰好也是 target ,那么这个节点也应该被删除。 也就是说,你需要重复此过程直到不能继续删…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们先判断 节点是否为空,若为空,则返回空。 否则,递归地处理 的左右子树,即调用 `root.left = removeLeafNodes(root.left, target)` 和 `root.right = removeLeafNodes(root.right, target)`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一棵以 root 为根的二叉树和一个整数 target ,请你删除所有值为 target 的 叶子节点 。
注意,一旦删除值为 target 的叶子节点,它的父节点就可能变成叶子节点;如果新叶子节点的值恰好也是 target ,那么这个节点也应该被删除。
也就是说,你需要重复此过程直到不能继续删除。
示例 1:

输入:root = [1,2,3,2,null,2,4], target = 2 输出:[1,null,3,null,4] 解释: 上面左边的图中,绿色节点为叶子节点,且它们的值与 target 相同(同为 2 ),它们会被删除,得到中间的图。 有一个新的节点变成了叶子节点且它的值与 target 相同,所以将再次进行删除,从而得到最右边的图。
示例 2:

输入:root = [1,3,3,3,2], target = 3 输出:[1,3,null,null,2]
示例 3:

输入:root = [1,2,null,2,null,2], target = 2 输出:[1] 解释:每一步都删除一个绿色的叶子节点(值为 2)。
提示:
- 树中节点数量的范围是
[1, 3000]。 1 <= Node.val, target <= 1000
解题思路
方法一:递归
我们先判断 节点是否为空,若为空,则返回空。
否则,递归地处理 的左右子树,即调用 root.left = removeLeafNodes(root.left, target) 和 root.right = removeLeafNodes(root.right, target)。
然后判断 节点是否为叶子节点,即判断 和 是否为空,且 是否等于 。若是,则返回空,否则返回 。
时间复杂度 ,空间复杂度 。其中 为二叉树的节点个数。
# 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 removeLeafNodes(
self, root: Optional[TreeNode], target: int
) -> Optional[TreeNode]:
if root is None:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
if root.left is None and root.right is None and root.val == target:
return None
return root
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Understanding of DFS and its application in tree-based problems.
- question_mark
Ability to manage tree reconstruction and state tracking through recursion.
- question_mark
Experience in dealing with binary trees and edge cases like consecutive deletions.
常见陷阱
外企场景- error
Not properly handling the parent-child relationship after deletion, leading to missed deletions.
- error
Failing to account for edge cases where multiple deletions affect the tree structure.
- error
Incorrectly managing the recursive return values, which can result in incorrect tree reconstruction.
进阶变体
外企场景- arrow_right_alt
Modify the problem to remove nodes with any value instead of just leaf nodes.
- arrow_right_alt
Extend the problem to handle more complex tree structures with additional constraints.
- arrow_right_alt
Adjust the problem to return a list of deleted nodes instead of just the modified tree.