Order of Trees
Time limit1sMemory limit128 MB
Given n, print the n-th binary tree under a canonical ordering by node count and by (left subtree number, right subtree number) recursively.
- Level
Hard8 of 10
- Topics
- Combinatorics, Dynamic programming, Recursion, Math
- Solved
- No attempts yet
Problem
You can assign a number to every binary tree using the following process.
-
The empty tree has number .
-
The tree with a single node has number .
-
A binary tree with nodes always has a smaller number than any binary tree with nodes. In other words, a tree with fewer nodes gets a smaller number.
-
To order two trees that have the same number of nodes, consider a tree with left subtree and right subtree . This tree has a smaller number than any tree with the same number of nodes that satisfies at least one of the following:
- its left subtree has a larger number than , or
- its left subtree equals and its right subtree has a larger number than .
Equivalently, trees with the same number of nodes are sorted by the pair (number of the left subtree, number of the right subtree) in lexicographic order.
The first binary trees (numbers through ) and the th binary tree are shown below.
0 1 2 3 4 5 6 7 8 9 ... 20
X X X X X X X X X X
\ / \ \ / \ / / \ /
X X X X X X X X X X
\ / \ / \ / \
X X X X X X X
\
X
Given an integer , write a program that finds the -th binary tree.
Input
The input consists of several test cases. Each line contains one integer ().
When is given, the input ends and the program should terminate.
Output
For each test case, print the corresponding tree on its own line using the following rules.
Let and be the printed results of the left subtree and the right subtree , respectively.
- A tree with no children (a single leaf node) is printed as
X. - If neither nor is empty, print
(L')X(R'). - If is empty, print
X(R'). - If is empty, print
(L')X.