VOOZH about

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

⇱ Construct Ancestor Matrix from a Given Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct Ancestor Matrix from a Given Binary Tree

Last Updated : 23 Jul, 2025

Given a Binary Tree where all values are from 0 to n-1.  Construct 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

Examples:

Input:

👁 construct-ancestor-matrix-from-a-given-binary-tree-1

Output: {{0 1 1}
{0 0 0}
{0 0 0}}

Input:

👁 construct-ancestor-matrix-from-a-given-binary-tree-2

Output: {{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}}

[Expected Approach - 1] Using Pre-Order traversal and Ancestor Array - O(n^2) Time and O(n^2) Space

The idea is to traverse the tree. While traversing, keep track of ancestors in an array. When we visit a node, we add it to ancestor array and consider the corresponding row in the adjacency matrix. We mark all ancestors in its row as 1. Once a node and all its children are processed, we remove the node from ancestor array.

Below is the implementation of above approach:


Output
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 

[Expected Approach - 2] Using Post-Order Traversal - O(n^2) Time and O(h) Space

The idea is to perform recursive traversal of the binary tree. For each node, process the left and right nodes. Set current node as ancestor of all nodes for which left and right nodes are ancestors. Then set current node as ancestor of left and right node.

Below is the implementation of the above approach:


Output
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 

Related articles:

Comment
Article Tags:
Article Tags: