Update 0669.修剪二叉搜索树.md

This commit is contained in:
jianghongcheng
2023-05-23 21:43:40 -05:00
committed by GitHub
parent 731d1ca8aa
commit 53652744d2

View File

@ -271,64 +271,72 @@ class Solution {
## Python
**递归**
递归法(版本一)
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
'''
确认递归函数参数以及返回值返回更新后剪枝后的当前root节点
'''
# Base Case
if not root: return None
# 单层递归逻辑
if root is None:
return None
if root.val < low:
# 若当前root节点小于左界只考虑其右子树用于替代更新后的其本身抛弃其左子树整体
# 寻找符合区间 [low, high] 的节点
return self.trimBST(root.right, low, high)
if high < root.val:
# 若当前root节点大于右界只考虑其左子树用于替代更新后的其本身抛弃其右子树整体
if root.val > high:
# 寻找符合区间 [low, high] 的节点
return self.trimBST(root.left, low, high)
if low <= root.val <= high:
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
# 返回更新后的剪枝过的当前节点root
root.left = self.trimBST(root.left, low, high) # root.left 接入符合条件的左孩子
root.right = self.trimBST(root.right, low, high) # root.right 接入符合条件的右孩子
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的情况
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
if root is None:
return None
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val > 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
```
迭代法
```python
class Solution:
def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
if not root:
return None
# 处理头结点让root移动到[L, R] 范围内,注意是左闭右闭
while root and (root.val < L or root.val > R):
if root.val < L:
root = root.right # 小于L往右走
else:
root = root.left # 大于R往左走
cur = root
# 此时root已经在[L, R] 范围内处理左孩子元素小于L的情况
while cur:
while cur.left and cur.left.val < low:
while cur.left and cur.left.val < L:
cur.left = cur.left.right
cur = cur.left
# 此时root已经在[L, R] 范围内处理右孩子大于R的情况
cur = root
# 此时root已经在[L, R] 范围内处理右孩子大于R的情况
while cur:
while cur.right and cur.right.val > high:
while cur.right and cur.right.val > R:
cur.right = cur.right.left
cur = cur.right
return root
```
## Go