题目:
给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树不应该改变保留在树中的元素的相对结构(即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在唯一的答案。
所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
/**************************法一:递归法******************************/
// TreeNode* trimBST(TreeNode* root, int low, int high)
// {
// if(root == nullptr)
// {
// return root;
// }
// // 中间的这两个 if 有点搞不明白为什么,这不是跟下面的两句一个意思吗
// // 笨蛋啊~没有这个怎么剪枝呢?这不就是为了剪枝吗?
// // 第一步
// if(root->val < low)
// {
// return trimBST(root->right,low,high);
// }
// // 第二步
// if(root->val > high)
// {
// return trimBST(root->left,low,high);
// }
// // 多想两边上面的两个 if 和这两句的意思。
// // 只看代码的话真的好难理解哇~
// // 第三步
// root->left = trimBST(root->left,low,high);
// root->right = trimBST(root->right,low,high);
// return root;
/*
对于单层递归逻辑这里,前两步和第三步的关系,刚开始真的很难想,其实现在可能也没有搞明白,
其实前两步就相当于把root变为符合 [low , high]这个区间的一个节点了
第三步是相当于对root的左右子树的修剪
*/
// }
/****************************法二:迭代法*************************/
TreeNode* trimBST(TreeNode* root, int low, int high)
{
if(root == nullptr)
{
return nullptr;
}
// 处理头结点,让 root 移动到区间范围内,注意是左闭右闭
while(root->val < low || root->val > high)
{
if(root->val <low)
{
// 小于 low 就往右走
root = root->right;
}
else
{
// 大于 high 就往左走
root = root->left;
}
// 当节点移动之后,要判断是否移动到了空节点处,
// 因为有一种情况是 所有节点都不在范围内
if(root == nullptr)
{
return nullptr;
}
}
TreeNode* cur = root;
// 到这一步,root 已经在区间范围内,处理左孩子元素小于 low 的情况
while(cur != nullptr)
{
while(cur->left != nullptr && cur->left->val < low)
{
cur->left = cur->left->right;
}
cur = cur->left;
}
// 再次将 root 赋值给 cur,处理右孩子大于 high 的情况
cur = root;
while(cur != nullptr)
{
while(cur->right != nullptr && cur->right->val >high)
{
cur->right = cur->right->left;
}
cur = cur->right;
}
return root;
}
};