题目:
题解:
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val > high) {
// 超过上界,剪掉右子树
root = root.left;
// 剪掉之后,继续剪左子树
root = trimBST(root, low, high);
return root;
}
if (root.val < low) {
// 小于下界,剪掉左子树
root = root.right;
// 剪掉之后,继续剪右子树
root = trimBST(root, low, high);
return root;
}
// 处于之间,递归剪左右子树
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
时间复杂度:O(N)