1. 修剪二叉搜索树(LeetCode 669)
1.1 问题理解与递归解法
这道题要求我们修剪二叉搜索树(BST),使其所有节点值都在给定范围[low, high]内。BST的特性是左子树节点值小于根节点,右子树节点值大于根节点。这个特性决定了我们的修剪策略:
当遇到节点值小于low时,其左子树所有节点必然都小于low,但右子树可能存在有效节点。因此我们只需保留右子树:
python复制if root.val < low:
return trimBST(root.right, low, high)
同理,当节点值大于high时,保留左子树:
python复制if root.val > high:
return trimBST(root.left, low, high)
对于在范围内的节点,我们需要递归处理其左右子树:
python复制root.left = trimBST(root.left, low, high)
root.right = trimBST(root.right, low, high)
1.2 实现细节与注意事项
完整Python实现:
python复制def trimBST(root, low, high):
if not root:
return None
if root.val < low:
return trimBST(root.right, low, high)
if root.val > high:
return trimBST(root.left, low, high)
root.left = trimBST(root.left, low, high)
root.right = trimBST(root.right, low, high)
return root
关键注意事项:
- 递归终止条件:遇到空节点直接返回None
- 返回值处理:必须用root.left/right接收递归返回值,这样才能正确更新树结构
- 时间复杂度:O(N),最坏情况需要访问所有节点
提示:在实际面试中,可以先用一个简单例子(如[1,0,2]修剪为
