diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index ac36509f..1fd6fce0 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -299,6 +299,32 @@ class Solution: return root ``` +**迭代** +```python +class Solution: + def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: + if not root: return root + # 处理头结点,让root移动到[L, R] 范围内,注意是左闭右开 + while root and (root.val < low or root.val > high): + if root.val < low: # 小于L往右走 + root = root.right + else: # 大于R往左走 + root = root.left + # 此时root已经在[L, R] 范围内,处理左孩子元素小于L的情况 + cur = root + while cur: + while cur.left and cur.left.val < low: + cur.left = cur.left.right + cur = cur.left + # 此时root已经在[L, R] 范围内,处理右孩子大于R的情况 + cur = root + while cur: + while cur.right and cur.right.val > high: + cur.right = cur.right.left + cur = cur.right + return root +``` + ## Go ```go