https://leetcode.cn/problems/trim-a-binary-search-tree/
给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。
所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。
示例 1:
输入:root = [1,0,2], low = 1, high = 2
输出:[1,null,2]
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
# 星级:☆☆☆☆
# 标签:递归
# if not root:
# return
# if root.val < low: # 当前值小于low,只考虑右子树
# return self.trimBST(root.right, low, high)
# if root.val > high: # 当前值大于high,只考虑左子树
# return self.trimBST(root.left, low, high)
# root.left = self.trimBST(root.left, low, high)
# root.right = self.trimBST(root.right, low, high)
# return root
# 标签:迭代
# 先找到一个符合[low,high]区间的节点,然后再修剪它的左右子树
while root and (root.val < low or root.val > high):
if root.val < low:
root = root.right
else:
root = root.left
if not root:
return
cur = root
while cur.left:
if cur.left.val < low:
cur.left = cur.left.right
else:
cur = cur.left
cur = root
while cur.right:
if cur.right.val > high:
cur.right = cur.right.left
else:
cur = cur.right
return root