题目描述
Category:Easy Tree
Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
题目理解
给定一棵二叉搜索树和最大最小值边界(L和R),修剪该二叉搜索树,使树中所有值均位于[L, R] (R >= L) 范围之内。可以改变树的根节点,返回修剪后二叉搜索树的新根节点。
解题思路
递归
如果root的值比R大,说明root以及其所有右节点都不在这个区间内,向左边搜索。如果root的值比L小,,说明root以及其所有左节点都不在这个区间内,向右边搜索。如果root正好在这个区间内,那么分别对它的左右子树进行裁剪。
思路借鉴:https://blog.csdn.net/fuxuemingzhu/article/details/83869684#_57
class Solution:
# Runtime: 108ms 5.00% MemoryUsage: 17MB 100.00%
def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
if not root:
return None
if root.val > R:
return self.trimBST(root.left, L, R)
elif root.val < L:
return self.trimBST(root.right, L, R)
else:
root.left = self.trimBST(root.left, L, R)
root.right = self.trimBST(root.right, L, R)
return root
永远学不会递归的zz已上线
Time
2020.3.22 这时间???这是真实的???我懵了