Turning a Tree
InterviewTime limit1sMemory limit1024 MB
Reroot a given ordered tree at a specified leaf so the counter-clockwise order of neighbors at each node stays the same, then print the new tree.
- Level
Medium6 of 10
- Topics
- Tree, DFS, Implementation, Recursion
- Solved
- No attempts yet
Problem
You are given a tree whose nodes are numbered . Node is the root, and for every node the ordered list of its children (from left to right) is given.
Lift a leaf of this tree so that it becomes the new root, keeping every edge intact — in particular, keeping the relative rotational order of the edges around each node unchanged. Output the resulting tree.
For example, starting from the tree on the left below and making the leaf the new root, we obtain the tree in the middle. The tree on the right would be wrong: around node the neighbours, read counter-clockwise, are in the original tree, but there.
1 3 3
/|\ | |
2 3 4 1 1
/ \ / \
4 2 2 4
Here a tree is a connected acyclic graph and node is its root; see Tree (data structure).
Input
The first line contains two integers: the number of nodes () and the index of the leaf that becomes the new root ().
Each of the next lines describes one node of the original tree. The -th line begins with , the number of children of node , followed by the indices of those children listed from left to right.
Output
Print exactly lines describing the new tree, using the same per-node format as the input. The -th line begins with the number of children of node in the new tree, followed by those children listed from left to right.
Hint
Take the first example, where leaf of the star (node with children ) becomes the new root:
- Node now has children: nodes and , in this order.
- Node has no children.
- Node has child: node .
- Node has no children.