思路
- 何时只修剪左子树?——右子树全部超出范围,即根节点大于上界
- 何时只修剪右子树?——左子树全部超过范围,即根节点小于上界
- 何时共同修建左右子树?——根节点未超出范围,进行共同修建并连接
代码
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==nullptr) return nullptr;
if(root->val >high)
return trimBST(root->left,low,high);
else if(root->val <low)
return trimBST(root->right,low,high);
else{
root->left=trimBST(root->left,low,high);
root->right=trimBST(root->right,low,high);
return root;
}
}
};