![在这里插入图片描述](https://img-blog.csdnimg.cn/20201022091514280.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JlbndlaXlpMTQ4Nw==,size_16,color_FFFFFF,t_70#pic_center)
递归
class Solution {
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;
}
}
迭代
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) return null;
while (root.val < low || root.val > high) {
if (root.val < low) root = root.right;
else root = root.left;
}
TreeNode cur = root;
while (cur != null) {
while (cur.left != null && cur.left.val < low) {
cur.left = cur.left.right;
}
cur = cur.left;
}
cur = root;
while (cur != null) {
while (cur.right != null && cur.right.val > high) {
cur.right = cur.right.left;
}
cur = cur.right;
}
return root;
}
}