mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Update 0669.修剪二叉搜索树.md 添加迭代法python3代码
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user