669. 修剪二叉搜索树 - 力扣(LeetCode) (leetcode-cn.com)
修剪二叉搜索树
递归
- 一棵树当前结点值小于low,那么保留右子树
- 一棵树当前节点值大于high,那么保留左子树
- 一棵树当前节点值在[low, high] 之间, 保留当前树。
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
// 修剪到空结点时返回
if (!root) return nullptr;
// 如果左树需要修剪, 则返回右子树
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;
}
};
非递归
- 需要先判断头结点情况
- 再分别处理左右子树
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (!root) return nullptr;
TreeNode* cur;
// 头结点需要修剪
while (root && (root->val < low || root->val > high)) {
if (root->val < low) root = root->right;
else root = root->left;
}
// 修剪左子树
cur = root;
while (cur) {
while (cur->left && cur->left->val < low) {
cur->left = cur->left->right;
}
cur = cur->left;
}
// 修剪右子树
cur = root;
while (cur) {
while (cur->right && cur->right->val > high) {
cur->right = cur->right->left;
}
cur = cur->right;
}
return root;
}
};