669. 修剪二叉搜索树
看题解做出来的
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return None
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val > high:
return self.trimBST(root.left, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
108.将有序数组转换为二叉搜索树
构造平衡搜索二叉树,从中间开始划分二叉树的左子树和右子树
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
return self.traversal(nums, 0, len(nums)-1)
def traversal(self, nums, left, right):
if left > right:
return None
mid = (right - left) // 2 + left
left = self.traversal(nums, left, mid-1)
right = self.traversal(nums, mid+1, right)
root = TreeNode(nums[mid], left, right)
return root
538.把二叉搜索树转换为累加树
右中左遍历,得到从大到小的序列,累计求和
本题中pre可以初始化为0,就不需要判断了
class Solution:
def __init__(self):
self.pre = None
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
self.convertBST(root.right)
if self.pre is not None:
root.val += self.pre
self.pre = root.val
self.convertBST(root.left)
return root