1. 题目
2. 思路
(1) 递归
- 若根结点的值在区间内,则分别对左右子树进行递归检查;若根结点的值小于最小值,则令根结点指针指向右子树,并对右子树进行递归检查;若根结点的值大于最大值,则令根结点指针指向左子树,并对左子树进行递归检查。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
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 null;
}
if (root.val >= low && root.val <= high) {
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
} else if (root.val < low) {
root = trimBST(root.right, low, high);
} else {
root = trimBST(root.left, low, high);
}
return root;
}
}