669. 修剪二叉搜索树
给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。
递归思想,先找到边界值,就是区间终点,再处理终点的左子树和右子树。
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
//如果当前元素比边界值最小值小,则去当前元素右子树找较大值
if (root.val < low) {
return trimBST(root.right, low, high);
}
//如果当前元素比边界值最大值大,则去寻找左子树,比当前值小一点的数
if (root.val > high) {
return trimBST(root.left, low, high);
}
//当前元素接收传来的处理后的新的左子树
root.left = trimBST(root.left, low, high);
//当前元素接收传来的处理后的新的右子树
root.right = trimBST(root.right, low, high);
return root;
}