All problems

Problem 917

Find Duplicate Subtrees

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

Problem

Two subtrees are duplicates if they have the same shape and the same values. Find every kind of subtree that appears at least twice in the tree. Print how many kinds there are, then one copy of each in level order, one per line, sorted by their level-order text. Serialise every subtree bottom-up into a string (or an id) and count the strings in a hash map; a kind is reported when its count reaches two.

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 number of duplicate kinds, then each kind's level-order tokens on its own line, sorted as text.

Constraints

1 <= number of nodes <= 5000; -200 <= value <= 200

Example input

10
1 2 3 4 null 2 4 null null 4

Example output

2
2 4
4

Explanation

In 1 2 3 4 null 2 4 null null 4, the subtree 4 appears three times and the subtree 2 with left child 4 appears twice. So there are 2 kinds: 2 4 and 4.

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

Previous: Binary Tree Pruning Next: Step-By-Step Directions From a Binary Tree Node to Another