@@ -264,20 +264,37 @@ class Solution {
264
264
265
265
```
266
266
267
- ## Python
268
-
267
+ ## Python
268
+ ** 递归 **
269
269
``` 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
271
276
class Solution :
272
277
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
281
298
```
282
299
283
300
## Go
0 commit comments