Skip to content

Commit e447076

Browse files
Merge pull request youngyangyang04#828 from casnz1601/patch-7
Update 0669.修剪二叉搜索树.md
2 parents a080032 + 0d99a39 commit e447076

File tree

1 file changed

+28
-11
lines changed

1 file changed

+28
-11
lines changed

problems/0669.修剪二叉搜索树.md

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -264,20 +264,37 @@ class Solution {
264264

265265
```
266266

267-
## Python
268-
267+
## Python
268+
**递归**
269269
```python3
270-
270+
# Definition for a binary tree node.
271+
# class TreeNode:
272+
# def __init__(self, val=0, left=None, right=None):
273+
# self.val = val
274+
# self.left = left
275+
# self.right = right
271276
class Solution:
272277
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
273-
if not root: return root
274-
if root.val < low:
275-
return self.trimBST(root.right,low,high) // 寻找符合区间[low, high]的节点
276-
if root.val > high:
277-
return self.trimBST(root.left,low,high) // 寻找符合区间[low, high]的节点
278-
root.left = self.trimBST(root.left,low,high) // root->left接入符合条件的左孩子
279-
root.right = self.trimBST(root.right,low,high) // root->right接入符合条件的右孩子
280-
return root
278+
'''
279+
确认递归函数参数以及返回值:返回更新后剪枝后的当前root节点
280+
'''
281+
# Base Case
282+
if not root: return None
283+
284+
# 单层递归逻辑
285+
if root.val < low:
286+
# 若当前root节点小于左界:只考虑其右子树,用于替代更新后的其本身,抛弃其左子树整体
287+
return self.trimBST(root.right, low, high)
288+
289+
if high < root.val:
290+
# 若当前root节点大于右界:只考虑其左子树,用于替代更新后的其本身,抛弃其右子树整体
291+
return self.trimBST(root.left, low, high)
292+
293+
if low <= root.val <= high:
294+
root.left = self.trimBST(root.left, low, high)
295+
root.right = self.trimBST(root.right, low, high)
296+
# 返回更新后的剪枝过的当前节点root
297+
return root
281298
```
282299

283300
## Go

0 commit comments

Comments
 (0)