Code the Tree
InterviewTime limit1sMemory limit128 MB
Parse a parenthesized tree description, then repeatedly remove the smallest-numbered leaf and print its neighbor to build the Prufer code.
- Level
Medium5 of 10
- Topics
- Tree, Implementation, Simulation, Greedy
- Solved
- No attempts yet
Problem
A tree (a connected graph with no cycles) has its vertices numbered with the integers . The Prufer code of such a tree is built as follows:
- Take the leaf (a vertex incident to exactly one edge) with the smallest number.
- Remove this leaf together with its incident edge, and write down the number of the vertex that was adjacent to it.
- Repeat this procedure on the remaining graph until only one vertex is left (this vertex always has number ).
The resulting sequence of written-down numbers is the Prufer code of the tree.
Your task is to compute the Prufer code of a given tree. A tree is described by a word of the language defined by the following grammar:
T ::= "(" N S ")"
S ::= " " T S
| empty
N ::= number
That is, a tree is surrounded by parentheses and begins with a number denoting the identifier of its root vertex, followed by arbitrarily many (possibly zero) subtrees, each separated by a single space character.
Note that, by this definition, the root of a tree may itself be a leaf. Choosing a root is only a matter of notation; what we are really dealing with is an unrooted tree.
Input
The input contains several test cases. Each test case describes one tree, written as above, on a single line. Input is terminated by end of file. You may assume that .
Output
For each test case, print a single line containing the Prufer code of the given tree. Separate consecutive numbers with a single space, and do not print any trailing space at the end of a line. When the code is empty, so print an empty line for that test case.