学习资料:https://programmercarl.com/0669.修剪二叉搜索树.html#算法公开课
学习记录:
669.修剪二叉搜索树(直接在原函数上操作,要根据情况用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 trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return None
if root.val < low:
right = self.trimBST(root.right, low, high)
return right
if root.val > high:
left = self.trimBST(root.left, low, high)
return left
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root
108.将有序数组转换为二叉搜索树(前序构造,加traversal函数:取数组中值作为根节点,中左右的构造二叉树)
点击查看代码
# 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 traversal(self, nums, left, right):
if left>right:
return None
# 找到中间位置作为根节点
mid = left + (right-left)//2
# 构建二叉树
root = TreeNode(nums[mid])
# 选取左闭右闭的区间
root.left = self.traversal(nums, left, mid-1)
root.right = self.traversal(nums, mid+1, right)
return root
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
root = self.traversal(nums, 0, len(nums)-1)
return root
538.把二叉搜索树转换为累加树(处理一个节点的方法是把树中比该节点值大的都加给这个节点;双指针;加一个traversal函数,不用返回值;从大到小,用右中左遍历顺序)
点击查看代码
# 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]:
self.pre = 0 # 初始pre指向最大值指向的NULL,则为0
self.traversal(root)
return root
def traversal(self, cur):
# 不用返回什么,只是在处理self
if not cur:
return
# 按顺序要反着来遍历,从最大的开始,那大的加给小的值
# 所以用右中左
self.traversal(cur.right)
# 双指针,pre的下一位是cur
cur.val += self.pre
self.pre = cur.val
self.traversal(cur.left)
PS:二叉树终于学完了,也太多了,训练营已经过去三分之一,坚持就是胜利!二叉树学的比较完善
原来周六也要学习啊,不愧是996的行业技能。今天水过去了,✌
今天吃了大餐,越做题越撑,太爽了。清蒸鲈鱼、回锅肉、包子、面条、清炒油麦菜、核桃、柚子、葡萄