0

Recently, I'm asked to write a program to solve a problem below.
Describe

Given a tree, two requirements,

  1. Traverse all nodes starting from root node. In the same time, you should guarantee every edge has been visited twice.
  2. Especially, leaf nodes should be visited as the order given.

Input

  • first line: integer K, represents number of nodes, K >= 1 && K <= 300
  • K-1 lines: each line contains two integers, represents an edge(Node ID is 1, 2, 3 .., 1 represents ID of root node).
  • last line: All the leaf nodes in order(leaf nodes should be visited in this order).

Output

If you can traverse the tree meeting two requirements above, outputs that node sequence. Otherwise, outputs -1

Two samples:

Input 1:
3
1 2
2 3
3
output is:
1 2 3 2 1
input1

Input 2:
6
1 2
1 3
2 4
4 5
4 6
5 3 6
output is:
-1
input2

Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
hel
  • 581
  • 10
  • 26
  • How about inverting the tree first. And then start traversing from root to the leaf. I am assuming there is a single root node.So in that case after inverting there will be a single leaf node. and three root nodes. Store the path from each root node and keep count of each node traversed.When count exceeds 2 for any node then return false. – Rudrani Angira Jul 27 '16 at 13:34

1 Answers1

2

Start by building a digraph.

Detecting whether it has cycles is a well-known problem. Return -1 if it has cycles. The remainder assumes there aren't.

Perform now an in-order traversal of the tree recursively, assigning order pairs, from the leaves to the root, to the nodes as follows.

  1. For a leaf node, say its order in the input is o. It's order pair is (o, o).

  2. For a non-leaf node, Check if there is an overlap between the order pairs of its children (say that one child has an order pair (1, 20), and another has an order pair (3, 4)). If there is an overlap, output -1. Otherwise, sort the children by the second item of their order pairs. If the order pairs of the children are (s1, e1), (s2, e2), ..., (sm, em), then the order pair of the node is (s1, em).

Finally, run again an in-order walk, this time by the order of the children. This traversal is the answer to the question.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185