538. 把二叉搜索树转换为累加树(中等)(LCR 054)

https://leetcode.cn/problems/convert-bst-to-greater-tree/

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。
注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同

示例 1:

class Solution:
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        # 星级:☆☆☆
        # 标签:右中左,反向中序遍历
        # 其实这就是一棵树,看起来别扭,换一个角度来看
        # 如果是一个有序数组[2, 5, 13],求从后到前的累加数组,也就是[20, 18, 13],是不是感觉这就简单了
        # 二叉搜索树最大节点出现在最右侧,因此从右开始遍历,不断累加,便符合要求,因此我们选择右中左
        # 从树中可以看出累加的顺序是右中左,所以我们需要反中序遍历这个二叉树,然后顺序累加就可以了
        sums = 0
        def traverse(node):
            nonlocal sums  # 必须用nonlocal,不能用global
            if not node:
                return
            traverse(node.right)
            sums += node.val
            node.val = sums
            traverse(node.left)
        traverse(root)
        return root

你可能感兴趣的:(二叉树,python,数据结构,算法,leetcode)