669. 修剪二叉搜索树
利用BST的性质
如果是不满足要求的点,就继续向下递归,不给root.left或root.right赋值
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
def traversal(root):
if not root:
return
if root.val > high:
return traversal(root.left)
if root.val < low:
return traversal(root.right)
if low <= root.val <= high:
root.left = traversal(root.left)
root.right = traversal(root.right)
return root
return traversal(root)
108. 将有序数组转换为二叉搜索树
类似二分、分治的思想,划分左右区间
递归实现
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
# 前序遍历构造
# 每次取区间的中间值构造
def construct(arr):
if not arr:
return
l = len(arr)
n = l // 2
root = TreeNode(arr[n])
root.left = construct(arr[:n])
root.right = construct(arr[n+1:])
# if n > 1:
# root.left = construct(arr[:n])
# root.right = construct(arr[n+1:])
# elif n == 1:
# node = root
# m = n + 1
# while n:
# n -= 1
# node.left = TreeNode(arr[n])
# node = node.left
# while l > m:
# node.right = TreeNode(arr[m])
# node = node.right
# m += 1
return root
return construct(nums)
538. 把二叉搜索树转换为累加树
注意到从右叶子节点开始累加,采用利用递归实现指定顺序的遍历
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# 后序遍历 累加
self.res = 0
def trav(root):
if not root:
return 0
trav(root.right)
self.res += root.val
root.val = self.res
trav(root.left)
trav(root)
return root