diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 23269bb7..09a512c4 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -264,20 +264,37 @@ class Solution { ``` -## Python - +## Python +**递归** ```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: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: - if not root: return root - if root.val < low: - return self.trimBST(root.right,low,high) // 寻找符合区间[low, high]的节点 - if root.val > high: - return self.trimBST(root.left,low,high) // 寻找符合区间[low, high]的节点 - root.left = self.trimBST(root.left,low,high) // root->left接入符合条件的左孩子 - root.right = self.trimBST(root.right,low,high) // root->right接入符合条件的右孩子 - return root + ''' + 确认递归函数参数以及返回值:返回更新后剪枝后的当前root节点 + ''' + # Base Case + if not root: return None + + # 单层递归逻辑 + if root.val < low: + # 若当前root节点小于左界:只考虑其右子树,用于替代更新后的其本身,抛弃其左子树整体 + return self.trimBST(root.right, low, high) + + if high < root.val: + # 若当前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 ``` ## Go