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

 

 

 

例如:

 

输入: 原始二叉搜索树:
5
/ \
2 13

 

输出: 转换为累加树:
18
/ \
20 13

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def convertBST(self, root: TreeNode) -> TreeNode:
        s=0
        def dfs(root:TreeNode):
            nonlocal s
            if root:
                dfs(root.right)
                s+=root.val
                root.val=s
                dfs(root .left)
        dfs(root)
        return root