22修剪二叉搜索树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {//返回值是以root为根节点,修剪完的节点
//要移除节点就返回删除减点符合条件的子树,让删除节点的父节点对应来接就好了
//一个节点如果不在区间中,那么就分类讨论:比low小、比high大
if(root == null) return root;
if(root.val < low) {//root比low小,其左子树一定不符合规则
return trimBST(root.right, low, high);//返回trim完的右子树就好了
} else if(root.val > high) {//root比high大,其右子树一定不符合规则
return trimBST(root.left, low, high);//返回trim完的左子树就好了
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}