算法刷题打卡020 | 二叉树终篇

LeetCode 669 修剪二叉搜索树

题目链接:669. 修剪二叉搜索树 - 力扣(Leetcode)

乍看这道题会觉得需要进行两次修剪,每次修剪一边。但讲解中在递归中直接完成两次判断,说实话还没完全理解这个递归逻辑,以下代码就是参考讲解写的:

# 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:
            return self.trimBST(root.right, low, high)
        if root.val > high:
            return self.trimBST(root.left, low, high)
        # 左
        root.left = self.trimBST(root.left, low, high)
        # 右
        root.right = self.trimBST(root.right, low, high)
        return root

LeetCode 108 将有序数组转换为二叉搜索树

题目链接:108. 将有序数组转换为二叉搜索树 - 力扣(Leetcode)

要构建高度平衡的二叉搜索树,只需要每次用区间的中间节点为根:

# 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]:
        def dfs(start, end):
            # 左闭右开区间
            if end <= start:
                return None
            mid = start + (end - start) // 2
            node = TreeNode(nums[mid])
            node.left = dfs(start, mid)
            node.right = dfs(mid+1, end)
            return node
        
        root = dfs(0, len(nums))
        return root
        

LeetCode 538 把二叉搜索树转换为累加树

题目链接:538. 把二叉搜索树转换为累加树 - 力扣(Leetcode)

 双指针方法就能完美解决这个问题,题目要求是“每个节点 node 的新值等于原树中大于或等于 node.val 的值之和”,依旧是中序遍历,但需要把左右反过来:

# 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 __init__(self):
        self.pre = None

    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(node):
            if not node:
                return
            # 右
            dfs(node.right)
            # 中
            if self.pre:
                node.val += self.pre.val
            self.pre = node
            # 左    
            dfs(node.left)
        
        dfs(root)
        return root

二叉树小结

代码随想录 (programmercarl.com),这个总结表有助于复习二叉树的解题思路。

你可能感兴趣的:(刷题,算法,leetcode)