Update 0669.修剪二叉搜索树.md 添加迭代法python3代码

This commit is contained in:
Zehua Ren
2023-01-19 17:47:41 +08:00
committed by GitHub
parent 5bf5416013
commit cbc75c0084

View File

@ -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