递归
/**
* 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) {
if(root==null) return root;//递归终止条件
if(root.val > high){// 寻找符合区间[low, high]的节点
//这里做的就是修剪得工作,把不符合条件得节点抛弃,这里就是把left下面得节点向上抛
TreeNode left = trimBST(root.left,low,high);
return left;
}
if(root.val < low){// 寻找符合区间[low, high]的节点
TreeNode right = trimBST(root.right,low,high);
return right;
}
root.left = trimBST(root.left,low,high);// root->left接入符合条件的左孩子
root.right = trimBST(root.right,low,high);// root->right接入符合条件的右孩子
return root;
}
}