VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-tree-from-ancestor-matrix/

⇱ Construct tree from ancestor matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct tree from ancestor matrix

Last Updated : 23 Jul, 2025

Given an ancestor matrix mat[n][n] where the 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.

  1. It may be assumed that the input provided in the program is valid and the tree can be constructed out of it.
  2. Many Binary trees can be constructed from one input. The program will construct any one of them.

Examples:

Input: mat[][] = {{0, 1, 1},
{0, 0, 0},
{0, 0, 0}};

Output: There are different possible outputs because ancestor matrix doesn't store that which child is left and which is right, one of the ouput is shown below.

👁 Construct-Binary-Tree-from-Ancestor-Matrix-46


Input: mat[][] = { {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: There are different possible outputs because ancestor matrix doesn't store that which child is left and which is right, one of the ouput is shown below.

👁 Construct-Binary-Tree-from-Ancestor-Matrix-47

Approach:

The idea is to use the below observations to construct the binary tree from the leaf nodes to the root node. Starting from leaf values, construct the corresponding node and check all its successor node. If any successor node does not have a parent node, then link the current node to that node.

Observations used in the solution: 

  1. The rows that correspond to leaves have all 0's
  2. The row that corresponds to root has maximum number of 1's.
  3. Count of 1's in i'th row indicates number of descendants of node i.

Step by step approach:

  • Create an array of node pointers node[].
  • Store row numbers that correspond to a given count.
  • Process all entries of map from smallest count to largest (Note that entries in map 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:


Output
0 1 4 5 3 2 

Time Complexity: O(n^2), where n is the number of nodes in the tree.
Auxiliary Space: O(n)

Please refer to this article for Top-Down approach: Construct Binary Tree from Ancestor Matrix | Top Down Approach

Comment
Article Tags:
Article Tags: