![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ebcde24d44d58464cdc62afc3e0b5739.png)
原题链接
- 如下
- 递归。。。。。。
- 二刷:经典的递归方法,假设递归函数能解决某个问题
- 在不同情况下调用递归函数,传入的限定条件 low 和 high 是不变的
本题是修剪二叉搜索树,与LeetCode 450 删除二叉搜索树不同
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/444e32acee66f8b4e982c5cb5feb1839.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ab8bdfddcecf0c489275c7c794923fd5.png)
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root == null) return null;
if(root.val < low){
root = root.right;
return trimBST(root, low, high);
}else if(root.val > high){
root = root.left;
return trimBST(root, low, high);
}else{
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
}
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low) {
root = root.right;
root = trimBST(root, low, high);
} else if (root.val > high) {
root = root.left;
root = trimBST(root, low, high);
} else {
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
}
return root;
}
}