day 23 补卡
Leetcode 669. Trim a Binary Search Tree
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)
if low <= root.val <= high:
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
Leetcode 108. Convert Sorted Array to Binary Search Tree
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def tree(nums):
if len(nums)==0: return None
if len(nums)==1: return TreeNode(nums[0])
root = TreeNode(nums[len(nums)//2])
left = nums[:len(nums)//2]
right = nums[len(nums)//2+1:]
root.left = tree(left)
root.right = tree(right)
return root
root = tree(nums)
return root
Leetcode 538. Convert BST to Greater Tree
右左中
class Solution:
def __init__(self):
self.count = 0
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root == None: return
self.convertBST(root.right)
self.count+=root.val
root.val = self.count
self.convertBST(root.left)
return root