1. 题目
2. 方法一递归
2.1. 代码
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(root==NULL) return root;
if((root->val)>R) return trimBST(root->left,L,R);
if((root->val)<L) return trimBST(root->right,L,R);
root->left=trimBST(root->left,L,R);
root->right=trimBST(root->right,L,R);
return root;
}
};
2.2. 结果
3. 方法一非递归
3.1. 代码
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
queue<TreeNode*> temp;
while(root!=NULL&&((root->val)<L||(root->val)>R)){
if(root->val<L){
root=root->right;
continue;
}
if(root->val>R) root=root->left;
}
if(root==NULL) return root;
temp.push(root);
TreeNode* curr;
while(!temp.empty()){
curr=temp.front();
temp.pop();
while(curr->left!=NULL&&((curr->left->val)<L||(curr->left->val)>R)){
if((curr->left->val)<L) {
curr->left=curr->left->right;
continue;
}
if((curr->left->val)>R) {
curr->left=curr->left->left;
continue;
}
}
if(curr->left!=NULL) temp.push(curr->left);
while(curr->right!=NULL&&((curr->right->val)<L||(curr->right->val)>R)){
if((curr->right->val)<L) {
curr->right=curr->right->right;
continue;
}
if((curr->right->val)>R) {
curr->right=curr->right->left;
continue;
}
}
if(curr->right!=NULL) temp.push(curr->right);
}
return root;
}
};
3.2. 结果