Lost BSTs

The binary search tree (BST) is one of the most important data
structures. Remember that the fundamental property of a BST is that
every subtree is such that the elements in its left child are strictly
smaller than the element in the root, and the elements in its right
child are strictly larger than the element in the root. Below we can see
an example of BST of strings, where every key shows its level between
parentheses.

$$\pstree[levelsep=40pt,treesep=25pt]
{\Tcircle{\mbox{\scriptsize fly (1)}}}{
  \pstree{\Tcircle{\mbox{\scriptsize box (2)}}}
  {
    \Tcircle{\mbox{\scriptsize at (3)}}
    \pstree{\Tcircle{\mbox{\scriptsize dog (3)}}}
    {
      \Tcircle{\mbox{\scriptsize cat (4)}}
      \Tcircle{\mbox{\scriptsize dot (4)}}
    }
  }
  \pstree{\Tcircle{\mbox{\scriptsize go (2)}}}
  {
    \Tn
    \pstree{\Tcircle{\mbox{\scriptsize it (3)}}}
    {
      \Tcircle{\mbox{\scriptsize hi (4)}}
      \Tn
    }
  }
}$$

Given all the pairs of string and level, in any order, can you
reconstruct the tree?

Input

Input consists of several cases. Every case begins with the number of
nodes n, followed by n pairs (string, level). Assume 1 ≤ n ≤ 10⁴, that
each string has between one and five lowercase letters, and that the
given information defines a correct BST.

Output

For every case, print the preorder of the BST. Print ‘-’ for every empty
subtree. Print a line with 10 dashes at the end of every case.

Problem information

Author: Jordi Petit

Generation: 2026-01-25T10:09:29.722Z

© Jutge.org, 2006–2026.
https://jutge.org
