Given an N × N ancestor matrix, whose cell (i, j) has the value true if i is the ancestor of j in a binary tree, construct a binary tree from it where binary tree nodes are labeled from 0 to N-1.

Please note that there may be several binary trees constructed out of a single matrix since the ancestor matrix doesn’t specify which child is left and which is right.

 
For example,

Input:
 
0  0  0  0  0
1  0  0  0  0
0  0  0  1  0
0  0  0  0  0
1  1  1  1  0
 
Output:
 
Any one of the following trees
 
      4              4             4
   /    \           / \          /   \
  1      2   OR   2    1    OR  1     2  OR …
 /     /         /      \        \    /
0     3         3        0        0  3

Practice this problem

We start by creating an array of pointers to store the binary tree nodes. Since the total number of set values in the i'th row indicates the total number of descendants of node i, store row numbers corresponding to a given count in a multimap. We then process the multimap entries in sorted order (smallest value first), and for each entry, assign a new node against the current row in the array. If it is a non-leaf node (having non-zero value), set the left/right child to its descendant’s nodes whose parents are not set (there can be at-max two such nodes if the given ancestor matrix is correct). Finally, return the last processed node, which has a maximum value and would be the root of the binary tree.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

0 1 4 3 2

Java


Download  Run Code

Output:

0 1 4 3 2

Python


Download  Run Code

Output:

0 1 4 3 2

The time complexity of the above solution is O(N2) and requires O(N) extra space, where N × N are dimensions of the ancestor matrix.

 
Author: Aditya Goel