0669. 修剪二叉搜索树【中等】
1. 📝 题目描述
给你二叉搜索树的根节点 root,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案。
所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。
示例 1:

txt
输入:root = [1,0,2], low = 1, high = 2
输出:[1,null,2]1
2
2
示例 2:

txt
输入:root = [3,0,4,null,2,null,null,1], low = 1, high = 3
输出:[3,2,null,1]1
2
2
提示:
- 树中节点数在范围
[1, 10^4]内 0 <= Node.val <= 10^4- 树中每个节点的值都是 唯一 的
- 题目数据保证输入是一棵有效的二叉搜索树
0 <= low <= high <= 10^4
2. 🎯 s.1 - 递归
c
struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
if (!root) return NULL;
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;
}1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
js
/**
* @param {TreeNode} root
* @param {number} low
* @param {number} high
* @return {TreeNode}
*/
var trimBST = function (root, low, high) {
if (!root) return null
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
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
py
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return None
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val > high:
return self.trimBST(root.left, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- 时间复杂度:
,其中 n 是节点数 - 空间复杂度:
,递归栈深度
算法思路:
- 利用 BST 性质递归修剪
- 当前节点值 < low,则左子树全部丢弃,返回修剪后的右子树
- 当前节点值 > high,则右子树全部丢弃,返回修剪后的左子树