All problems

Problem 615

Recover a Tree From Preorder Traversal

Hard · 30 pts · Tree, String, Stack

Problem

A pre-order traversal of a binary tree was written as a string: for each node, D dashes are printed (D is its depth, 0 for the root), followed by its value. If a node has only one child, that child is its left child. Rebuild the tree and print it in level order. Parse the string into (depth, value) pairs and keep a stack of the current path: pop until the stack size equals the new depth, then attach the node as the left child of the top if it has none, otherwise as the right child.

Input

A single string S describing the traversal, made of digits and dashes.

Output

Print the tree as level-order tokens separated by spaces, using null for missing children and without trailing nulls.

Constraints

1 <= number of nodes <= 1000; 1 <= value <= 10^9

Example input

1-2--3--4-5--6--7

Example output

1 2 5 3 4 6 7

Explanation

In 1-2--3--4-5--6--7, the root 1 has children 2 and 5 (one dash each). Node 2 has children 3 and 4, and node 5 has children 6 and 7, so the tree in level order is 1 2 5 3 4 6 7.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Binary Tree Cameras Next: Path Sum III