From cbc75c008452a9ac0de0b580a30a4a1d9ec969b5 Mon Sep 17 00:00:00 2001 From: Zehua Ren <48848908+Renzehua1998@users.noreply.github.com> Date: Thu, 19 Jan 2023 17:47:41 +0800 Subject: [PATCH] =?UTF-8?q?Update=200669.=E4=BF=AE=E5=89=AA=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E6=B3=95python3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0669.修剪二叉搜索树.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) 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