解题思路:
不能在发现节点不在范围时直接return null,还需要继续向下遍历,因为它的子节点可能在范围内,也可以重新作为新树的一部分
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
return recur(root, low, high);
}
public TreeNode recur(TreeNode root, int low, int high) {
if (root == null) return null;
if (root.val < low) {
TreeNode right = recur(root.right, low, high);
return right;
}
if (root.val > high) {
TreeNode left = recur(root.left, low, high);
return left;
}
root.left = recur(root.left, low, high);
root.right = recur(root.right, low, high);
return root;
}
}