【LeetCode 47】669.修剪二叉搜索树
一、题意
二、解答过程
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==NULL) return NULL;
//当前节点的元素小于low,去寻找右子树,返回右子树符合条件的节点
if(root->val<low)
{
//寻找符合[low,high]区间的节点
TreeNode* right=trimBST(root->right,low,high);
return right;
}
//当前节点的元素大于low,去寻找左子树,返回左子树符合条件的节点
if(root->val>high)
{
//寻找符合[low,high]区间的节点
TreeNode* left=trimBST(root->left,low,high);
return left;
}
//遍历左右子树
root->left=trimBST(root->left,low,high);
root->right=trimBST(root->right,low,high);
return root;
}
};