All problems

Problem 606

Convert BST to Greater Sum Tree

Medium · 20 pts · Tree, Binary Search Tree, Depth-First Search

Problem

Given a binary search tree with distinct values, replace the value of every node with the sum of all values in the tree that are greater than or equal to it. The shape of the tree stays the same. Print the new tree in the same level-order format as the input. A reverse in-order traversal (right subtree, node, left subtree) visits values from largest to smallest, so a running total gives each new value directly.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.

Output

Print the new tree as level-order tokens separated by spaces, using null for missing children and without trailing nulls.

Constraints

1 <= number of nodes <= 10000; 0 <= value <= 1000; values are distinct

Example input

15
4 1 6 0 2 5 7 null null null 3 null null null 8

Example output

30 36 21 36 35 26 15 null null null 33 null null null 8

Explanation

In the tree 4 1 6 0 2 5 7 null null null 3 null null null 8, the node 6 becomes 6 + 7 + 8 = 21 and the root 4 becomes 4 + 5 + 6 + 7 + 8 = 30. Doing this for every node gives 30 36 21 36 35 26 15 null null null 33 null null null 8.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Absolute Difference in BST Next: Lowest Common Ancestor of Deepest Leaves