原题:#669_修剪二叉搜索树
- 判断当前节点:
- 若当前节点值大于R,则将其修剪后的左子树作为最新树,自己及其右子树剪掉
- 若当前节点值小于R,则将其修剪后的右子树作为最新树,自己及其左子树剪掉
- 若当前节点值在[L,R]范围内,则只需要继续修剪左、右子树即可
public TreeNode trimBST(TreeNode root, int L, int R) {
if (root == null) return null;
//如果当前节点值小于L,则直接修改右子树当成根节点
if (root.val < L) return trimBST(root.right, L, R);
//如果当前节点值小于L,则直接修改右子树当成根节点
if (root.val > R) return trimBST(root.left, L, R);
//如果左右子树都在范围内(即不符合上述两种条件),则递归修剪左右子树
root.left = trimBST(root.left, L, R);
root.right = trimBST(root.right, L, R);
return root;
}