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

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

  1. 记录所有点的值排序
  2. 更新
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import heapq
class Solution:
    def convertBST(self, root: TreeNode) -> TreeNode:
        A = []
        def dfs(root):
            if root:
                heapq.heappush(A, root.val)
                dfs(root.left)
                dfs(root.right)
        dfs(root)        
        prefix = [0]
        A = sorted(A)
        for x in A:
            prefix.append(x + prefix[-1])
            
        def modify(root):
            if root:
                i = bisect.bisect_right(A, root.val)
                root.val += prefix[-1] - prefix[i]
                modify(root.left)
                modify(root.right)
        modify(root)        
        return root
                

©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页