Construct tree from ancestor matrix
Given an ancestor matrix mat[n][n] where Ancestor matrix is defined as below.
mat[i][j] = 1 if i is ancestor of j mat[i][j] = 0, otherwise
Construct a Binary Tree from a given ancestor matrix where all its values of nodes are from 0 to n-1.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- It may be assumed that the input provided the program is valid and tree can be constructed out of it.
- Many Binary trees can be constructed from one input. The program will construct any one of them.
Input: 0 1 1 0 0 0 0 0 0 Output: Root of one of the below trees. 0 0 / \ OR / \ 1 2 2 1 Input: 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 Output: Root of one of the below trees. 5 5 5 / \ / \ / \ 1 2 OR 2 1 OR 1 2 OR .... / \ / / / \ / \ / 0 4 3 3 0 4 4 0 3 There are different possible outputs because ancestor matrix doesn't store that which child is left and which is right.
We strongly recommend you to minimize your browser and try this yourself first.
Observations used in the solution:
- The rows that correspond to leaves have all 0’s
- The row that corresponds to root has maximum number of 1’s.
- Count of 1’s in i’th row indicates number of descendants of node i.
The idea is to construct the tree in bottom up manner.
- Create an array of node pointers node.
- Store row numbers that correspond to a given count. We have used multimap for this purpose.
- Process all entries of multimap from smallest count to largest (Note that entries in map and multimap can be traversed in sorted order). Do following for every entry.
- Create a new node for current row number.
- If this node is not a leaf node, consider all those descendants of it whose parent is not set, make current node as its parent.
- The last processed node (node with maximum sum) is root of tree.
Below is the implementation of the above approach:
0 1 4 5 3 2
Note that we can also use an array of vectors in place of multimap. We have used multimap for simplicity. Array of vectors would improve performance as inserting and accessing elements would take O(1) time.
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above