Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
删除二叉搜索树中某些节点,将所有节点的值保持在[L,R]之间,并且在完成删除操作之后,仍能保持为一颗二叉搜索树。
主要思路:
BST: left < root->val < right. If L>root->val or Rval then one side of subtree is out of range [L, R] and we call trim only on the other side. Otherwise recursively call on both sides
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(!root) return NULL;
if(L>root->val){
return trimBST(root->right,L,R);
}
if(R < root->val){
return trimBST(root->left,L,R);
}
root->left = trimBST(root->left,L,R);
root->right = trimBST(root->right,L,R);
return root;
}