All problems

Problem 920

Most Frequent Subtree Sum

Medium · 20 pts · Tree, Hash Table, Depth-First Search

Problem

The subtree sum of a node is the sum of all values in its subtree, including the node itself. Find the subtree sum that occurs most often over all nodes. If several sums tie for the highest frequency, print all of them in increasing order. Compute the subtree sums with one post-order traversal and count them in a hash map.

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 most frequent subtree sums in increasing order, separated by spaces.

Constraints

1 <= number of nodes <= 10000; -10^5 <= value <= 10^5

Example input

3
5 2 -3

Example output

-3 2 4

Explanation

In 5 2 -3, the subtree sums are 2, -3 and 5 + 2 - 3 = 4, each appearing once. All tie, so the answer is -3 2 4.

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

Previous: Reverse Odd Levels of Binary Tree Next: Closest Binary Search Tree Value