力扣-二叉树-669 修剪二叉搜索树
思路
和之前的二叉搜索树类似,再寻找不符合条件的节点过程中,用上一层的左或者右接住下一层return回来的根节点
代码
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr) return nullptr;
if(root->val < low){
return trimBST(root->right, low, high);
}else if(root->val > high){
return trimBST(root->left, low, high);
}else{
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
}
return root;
}
};