1. Description
Given a binary search tree and the interval [L, R].
Change the BST so that all elements lies in [L, R].
2. Solution
If the root's value is in the range [L, R], then trim its left and right child.
If the root's value is smaller than L, then return the trimmed right child tree.
If the root's value is bigger than R, then return the trimmed left child tree.
3. Code
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(!root) return NULL;
if(root->val>=L&&root->val<=R){
root->left = trimBST(root->left,L,R);
root->right = trimBST(root->right,L,R);
return root;
}
else if(root->val<L){
return trimBST(root->right,L,R);
}
else
return trimBST(root->left,L,R);
}