You are given the Ancestor matrix of a Binary tree, write an Algorithm to construct the corresponding tree.

**For example**, the below tree:

The order of rows in the above matrix is not defined. I have kept it in the ascending order because the data in our nodes is numeric and can be ordered.

Essentially, in the ancestor matrix, each node has a row and a column (may not be the same). The value at a[i][j] will be 1 iff node of Node representing **j‘**th column is the ancestor of node representing the **i**‘th row.

Write an algorithm that can construct the binary tree from a given Ancestor matrix.

**Note: ***Since we don’t have information about whether a child is a left child or a right child, the tree which gets constructed will be unordered Binary tree(i.e, there can be max two children of a node but they will not be ordered as left or right).*

### Solution:

- Add 1 more column in the matrix which contain the sum of all the elements in that row:
- Find the row, which has all zeros (for which sum[i] = 0). lets call this node r (root of the tree)
- Q.enqueue ( r);
- while (!Q.isempty)
- temp = Q.dequeue();
- remove both
**row & column**of the temp node and update the sum column accordingly (ideally all the elements in the Sum column should decrease). - Look for all the rows for which Sum[i] == 0
- add them as children to node temp.
- Insert them at the end of the queue.

The Algorithm will proceed as shown in the below diagram:

10 / \ 5 30

10 / \ 5 30 / \ 4 8

can you provide me code for this ?

The time complexity of the algorithm is O(n2) right??

Is there any other efficient algorithm than this?

Awesome

Thanks Prasad

Hi Kamal, doesnt step 1 (sum of values in the row) directly give us the level of each node. I assume this is a BST (else there will be no one unique solution) which we can use to leverage whether the children are left / right at each level.

Or another train of thought was to just sort the nodes (inorder) and step 1 gives us the root. Inorder + root + BST => should be enough to reconstruct the tree

What are your comments on the above?

Hi Sai,

I have updated the post to make the algo more clear.. Step-1 gives us the information of which node is at which level.. but it does not give us any information about the parent child relationship (i.e Node 4 & 40 are at the same level, but their parent nodes are different)..

To get the parent-child relation, we have to subtract the values of corresponding nodes..

This algorithm is not for BST but any UN-ORDERED Binary tree.. It can very well be applied for tree where nodes data cannot be ordered.. The tree being unordered means, that whether a child is the left child or right child does not matter. Hence the two tree below are same

Since the tree may not necessarily be BST .. the example I have chosen may have confused you

hi can i pls have d code for this?

will try to put it in few days.. why don’t you try it out and put it in the comment or mail to me.