目录
学习目标
- 669. 修剪二叉搜索树
- 108.将有序数组转换为二叉搜索树
- 538.把二叉搜索树转换为累加树
- 总结篇
学习内容
669. 修剪二叉搜索树
669. 修剪二叉搜索树 - 力扣(LeetCode)https://leetcode.cn/problems/trim-a-binary-search-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:return root
if root.val<low:
root.right = self.trimBST(root.right,low,high)
return root.right
elif root.val>high:
root.left = self.trimBST(root.left,low,high)
return root.left
else:
root.left = self.trimBST(root.left,low,high)
root.right = self.trimBST(root.right,low,high)
return root
108.将有序数组转换为二叉搜索树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
n = len(nums)
if n==0:return
index = n//2
root = TreeNode(val = nums[index])
root.left = self.sortedArrayToBST(nums[0:index])
root.right = self.sortedArrayToBST(nums[index+1:n])
return root
538.把二叉搜索树转换为累加树
538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)https://leetcode.cn/problems/convert-bst-to-greater-tree/
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def tree(root):
nonlocal amount
if not root:return root
root.right = tree(root.right)
amount += root.val
root.val = amount
root.left = tree(root.left)
return root
amount = 0
return tree(root)
迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:return root
amount =0
stack = []
cur = root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.right
cur = stack.pop()
amount +=cur.val
cur.val = amount
cur = cur.left
return root
Morris解法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:return root
amount = 0
pre = root
cur = root
while pre:
# 连接根节点和右子树的最左侧叶子
if pre.right:
cur = pre.right
while cur.left and cur.left!=pre:
cur = cur.left
if not cur.left:
cur.left = pre
pre = pre.right
elif cur.left==pre:
amount+=pre.val
pre.val = amount
cur.left = None
pre = pre.left
else:
amount+=pre.val
pre.val = amount
pre = pre.left
return root
总结篇