2023.7.15
知道了如何删除二叉树节点的逻辑之后,这题就不难了。 可以参考删除二叉搜索树中的节点这篇文章。
下面直接上代码:
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr) return root;
root->left = trimBST(root->left,low,high);
root->right = trimBST(root->right,low,high);
if(root->val<low || root->val>high)
{
if(root->left==nullptr && root->right==nullptr)
{
return nullptr;
}
else if(root->left == nullptr)
{
return root->right;
}
else if(root->right == nullptr)
{
return root->left;
}
else
{
TreeNode* cur = root->right;
while(cur->left != nullptr)
{
cur = cur->left;
}
root->val = cur->val;
root->right = trimBST(root->right,low,high);
// cur->left = root->left;
// return root->right;
}
}
return root;
}
};