Restore a Binary Search Tree
InterviewTime limit2sMemory limit1024 MB
Given each node's value and depth, rebuild a binary search tree from them, or report -1 when no such tree exists.
- Level
Medium6 of 10
- Topics
- Sorting, Divide and conquer, Tree
- Solved
- No attempts yet
Problem
Chansol built a binary search tree in which each of the nodes holds an integer. In a binary search tree, for every node , every number in the left subtree of is less than the number in , and every number in the right subtree of is greater than the number in .
For every , Chansol recorded the depth of node and the integer written on node . All are distinct, and the root has depth 1. ()
Chansol lost the tree while attending the ICPC World Finals. Restore the binary search tree from the recorded information.
Input
The first line contains the number of nodes . ()
The next lines describe the nodes. For each , line contains the integer written on node and the depth of node , separated by a space. (, ) All are distinct.
Output
If the recorded information cannot be restored to a binary search tree, print -1.
Otherwise, print the structure of the tree over lines. Line contains the node numbers of the left child and the right child of node . If a child does not exist, print -1 in its place.
If several trees can be restored, print any of them.