#K75307. Convert BST to Greater Tree
Convert BST to Greater Tree
Convert BST to Greater Tree
You are given a binary search tree (BST) with integer values. Your task is to convert the BST into a "greater tree". In the greater tree, every node's new value is the sum of its original value and all the node values in the original BST that are greater than it.
More formally, for each node with original value x, update it to x + S, where S is the sum of all node values greater than x in the original BST. This can be achieved by performing a reverse in-order traversal (i.e., traverse right subtree, then node, then left subtree) and maintaining an accumulated sum.
For example, given the BST represented in level-order as 5,2,13
, the resulting greater tree will be 18,20,13
.
inputFormat
The input consists of a single line containing comma-separated values representing the binary tree in level-order. The keyword "null" is used to denote a missing node. Examples of valid inputs:
5,2,13
3,2,4,1
1
null
outputFormat
Output the greater tree using the same level-order format as the input, as a comma-separated string with no extra spaces. For an empty tree, output "null".## sample
5,2,13
18,20,13