mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
@ -265,18 +265,35 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Python
|
## Python
|
||||||
|
**递归**
|
||||||
```python3
|
```python3
|
||||||
|
# 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:
|
class Solution:
|
||||||
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
|
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
|
||||||
if not root: return root
|
'''
|
||||||
|
确认递归函数参数以及返回值:返回更新后剪枝后的当前root节点
|
||||||
|
'''
|
||||||
|
# Base Case
|
||||||
|
if not root: return None
|
||||||
|
|
||||||
|
# 单层递归逻辑
|
||||||
if root.val < low:
|
if root.val < low:
|
||||||
return self.trimBST(root.right,low,high) // 寻找符合区间[low, high]的节点
|
# 若当前root节点小于左界:只考虑其右子树,用于替代更新后的其本身,抛弃其左子树整体
|
||||||
if root.val > high:
|
return self.trimBST(root.right, low, high)
|
||||||
return self.trimBST(root.left,low,high) // 寻找符合区间[low, high]的节点
|
|
||||||
root.left = self.trimBST(root.left,low,high) // root->left接入符合条件的左孩子
|
if high < root.val:
|
||||||
root.right = self.trimBST(root.right,low,high) // root->right接入符合条件的右孩子
|
# 若当前root节点大于右界:只考虑其左子树,用于替代更新后的其本身,抛弃其右子树整体
|
||||||
|
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
|
||||||
return root
|
return root
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user