public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return root;
}
// 如果当前节点的值小于 最小值 则将右子节点赋给当前节点
//如果当前节点的值大于 最大值 则将左子节点赋给当前节点
while(root != null && (root.val < low || root.val > high )){
if(root != null && root.val < low) {
root = root.right;
}
if (root != null && root.val > high) {
root = root.left;
}
}
if(root != null){
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;
}
if (root.val < low) {
return trimBST(root.right, low, high);
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
// root在[low,high]范围内
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}