题目要求
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
题目分析及思路
题目给出一棵二叉搜索树,要求将它转成Greater Tree。定义Greater Tree的结点值为原树中的结点值加上所有比该结点值大的结点值。可使用递归方法,顺序为右根左,需定义一个全局的变量统计结点值的和。
python代码
# 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:
self.s = 0
def treesum(node):
if not node:
return
treesum(node.right)
node.val += self.s
self.s = node.val
treesum(node.left)
treesum(root)
return root