669. 修剪二叉搜索树
- 一些递归,有点点绕,但画了一下示意图就差不多能理清
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
dummy = TreeNode(high, left=root)
self.traversal(dummy, low, high)
return dummy.left
def traversal(self, root, low, high):
if not root: return
if root.val < low:
return self.traversal(root.right, low, high)
elif root.val > high:
return self.traversal(root.left, low, high)
else:
root.left = self.traversal(root.left, low, high)
root.right = self.traversal(root.right, low, high)
return root
- 不知道为什么最近陷入这个dummy的怪圈了。其实由于是递归,因此return递归返回的值就行了,返回的就是root。
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
return self.traversal(root, low, high)
def traversal(self, root, low, high):
if not root: return
if root.val < low:
return self.traversal(root.right, low, high)
elif root.val > high:
return self.traversal(root.left, low, high)
else:
root.left = self.traversal(root.left, low, high)
root.right = self.traversal(root.right, low, high)
return root
108.将有序数组转换为二叉搜索树
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
n = len(nums)
if n == 0: return None
mid_node = nums[n//2]
root = TreeNode(mid_node)
root.left = self.sortedArrayToBST(nums[:n//2])
root.right = self.sortedArrayToBST(nums[n//2+1:])
return root
538.把二叉搜索树转换为累加树
- 反中序的递归,累加。其实很简单,奈何自己递归还是有点想不明白
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.pre = 0
self.traversal(root)
return root
def traversal(self, cur):
if not cur: return 0
self.traversal(cur.right)
cur.val += self.pre
self.pre = cur.val
self.traversal(cur.left)