Construct Binary Tree from Ancestor Matrix | Top Down Approach (original) (raw)

Last Updated : 12 Jul, 2025

Given an ancestor matrix **mat[n][n] where the Ancestor matrix is defined as below.

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 store the number of **successor nodes for each node. Starting from the **root value (which will be ancestor for all nodes), create the corresponding node and set **sum value to -1. Then iterate through all its **successor values and find the index with with **maximum successor nodes. If index is not **-1, then create the **left node recursively using this index. Similarly, again iterate through the successor nodes and again find the index with maximum successor nodes. If this index is not -1, then use this index to recursively create the **right subtree.

Below is the implementation of the above approach:

C++ `

// C++ program to construct binary // tree from ancestor matrix. #include <bits/stdc++.h> using namespace std;

class Node { public: int data; Node *left, *right; Node(int x) { data = x; left = nullptr; right = nullptr; } };

Node *constructTree(int i, vector<vector> mat, vector &sum) {

// Create current node.
Node *root = new Node(i);

// Set sum[i] to -1 to ensure this
// node is only left or right node
// of its parent node.
sum[i] = -1;

// Variables for finding left node.
int leftIndex = -1;
int leftMaxi = -1;

// Traverse through all successor nodes and
// set left index to index with maximum number
// of successor nodes.
for (int j = 0; j < mat.size(); j++) {

    if (mat[i][j] == 1 && sum[j] > leftMaxi) {
        leftMaxi = sum[j];
        leftIndex = j;
    }
}

// If there is atleast one value, then create
// left subtree.
if (leftIndex != -1)
    root->left = constructTree(leftIndex, mat, sum);

// variables for right subtree.
int rightIndex = -1;
int rightMaxi = -1;

// Traverse through all successor nodes and
// set right index to index with maximum number
// of successor nodes. (Note: All the left subtree
// nodes will have -1 as value here).
for (int j = 0; j < mat.size(); j++) {
    if (mat[i][j] == 1 && sum[j] > rightMaxi) {
        rightMaxi = sum[j];
        rightIndex = j;
    }
}

// If right subtree exists.
if (rightIndex != -1)
    root->right = constructTree(rightIndex, mat, sum);

return root;

}

// Constructs tree from ancestor matrix Node *ancestorTree(vector<vector> mat) { int n = mat.size();

// Array to store number of
// successor nodes for each node.
vector<int> sum(n, 0);

int rootIndex;

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        sum[i] += mat[i][j];
    }

    // If sum[i] is equal to (n-1),
    // then it is the root node.
    if (sum[i] == n - 1)
        rootIndex = i;
}

Node *root = constructTree(rootIndex, mat, sum);

return root;

}

void printInorder(Node *node) { if (node == nullptr) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right); }

int main() { vector<vector> 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}};

Node *root = ancestorTree(mat);
printInorder(root);

return 0;

}

Java

// Java program to construct binary // tree from ancestor matrix. import java.util.*;

class Node { int data; Node left, right;

Node(int x) {
    data = x;
    left = null;
    right = null;
}

}

class GfG {

static Node constructTree(int i, 
ArrayList<ArrayList<Integer>> mat, ArrayList<Integer> sum) {

    // Create current node.
    Node root = new Node(i);

    // Set sum[i] to -1 to ensure this
    // node is only left or right node 
    // of its parent node.
    sum.set(i, -1);

    // Variables for finding left node.
    int leftIndex = -1;
    int leftMaxi = -1;

    // Traverse through all successor nodes and 
    // set left index to index with maximum number
    // of successor nodes.
    for (int j = 0; j < mat.size(); j++) {

        if (mat.get(i).get(j) == 1 && sum.get(j) > leftMaxi) {
            leftMaxi = sum.get(j);
            leftIndex = j;
        }
    }

    // If there is at least one value, then create 
    // left subtree.
    if (leftIndex != -1)
        root.left = constructTree(leftIndex, mat, sum);

    // Variables for right subtree.
    int rightIndex = -1;
    int rightMaxi = -1;

    // Traverse through all successor nodes and 
    // set right index to index with maximum number
    // of successor nodes. (Note: All the left subtree 
    // nodes will have -1 as value here).
    for (int j = 0; j < mat.size(); j++) {
        if (mat.get(i).get(j) == 1 && sum.get(j) > rightMaxi) {
            rightMaxi = sum.get(j);
            rightIndex = j;
        }
    }

    // If right subtree exists.
    if (rightIndex != -1)
        root.right = constructTree(rightIndex, mat, sum);

    return root;
}

static Node ancestorTree(ArrayList<ArrayList<Integer>> mat) {
    int n = mat.size();

    // Array to store number of 
    // successor nodes for each node.
    ArrayList<Integer> sum = new ArrayList<>
                              (Collections.nCopies(n, 0));

    int rootIndex = -1;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            sum.set(i, sum.get(i) + mat.get(i).get(j));
        }

        // If sum[i] is equal to (n-1),
        // then it is the root node.
        if (sum.get(i) == n - 1)
            rootIndex = i;
    }

    Node root = constructTree(rootIndex, mat, sum);

    return root;
}

static void printInorder(Node node) {
    if (node == null)
        return;
    printInorder(node.left);
    System.out.print(node.data + " ");
    printInorder(node.right);
}

public static void main(String[] args) {
  
    ArrayList<ArrayList<Integer>> mat = new ArrayList<>();
    mat.add(new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0, 0)));
    mat.add(new ArrayList<>(Arrays.asList(1, 0, 0, 0, 1, 0)));
    mat.add(new ArrayList<>(Arrays.asList(0, 0, 0, 1, 0, 0)));
    mat.add(new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0, 0)));
    mat.add(new ArrayList<>(Arrays.asList(0, 0, 0, 0, 0, 0)));
    mat.add(new ArrayList<>(Arrays.asList(1, 1, 1, 1, 1, 0)));

    Node root = ancestorTree(mat);

    printInorder(root);
}

}

Python

Python program to construct binary

tree from ancestor matrix.

class Node: def init(self, x): self.data = x self.left = None self.right = None

def constructTree(i, mat, sum):

# Create current node.
root = Node(i)

# Set sum[i] to -1 to ensure this
# node is only left or right node 
# of its parent node.
sum[i] = -1

# Variables for finding left node.
leftIndex = -1
leftMaxi = -1

# Traverse through all successor nodes and 
# set left index to index with maximum number
# of successor nodes.
for j in range(len(mat)):
    if mat[i][j] == 1 and sum[j] > leftMaxi:
        leftMaxi = sum[j]
        leftIndex = j

# If there is at least one value, then create 
# left subtree.
if leftIndex != -1:
    root.left = constructTree(leftIndex, mat, sum)

# Variables for right subtree.
rightIndex = -1
rightMaxi = -1

# Traverse through all successor nodes and 
# set right index to index with maximum number
# of successor nodes. (Note: All the left subtree 
# nodes will have -1 as value here).
for j in range(len(mat)):
    if mat[i][j] == 1 and sum[j] > rightMaxi:
        rightMaxi = sum[j]
        rightIndex = j

# If right subtree exists.
if rightIndex != -1:
    root.right = constructTree(rightIndex, mat, sum)

return root

def ancestorTree(mat): n = len(mat)

# Array to store number of 
# successor nodes for each node.
sum = [0] * n

rootIndex = -1

for i in range(n):
    for j in range(n):
        sum[i] += mat[i][j]

    # If sum[i] is equal to (n-1),
    # then it is the root node.
    if sum[i] == n - 1:
        rootIndex = i

root = constructTree(rootIndex, mat, sum)

return root

def printInorder(node): if not node: return printInorder(node.left) print(node.data, end=' ') printInorder(node.right)

if name == 'main': 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] ]

root = ancestorTree(mat)

printInorder(root)

C#

// C# program to construct binary // tree from ancestor matrix. using System; using System.Collections.Generic;

class Node { public int data; public Node left, right;

public Node(int x) {
    data = x;
    left = null;
    right = null;
}

}

class GfG {

static Node constructTree(int i, 
                          List<List<int>> mat, List<int> sum) {
    
    // Create current node.
    Node root = new Node(i);
    
    // Set sum[i] to -1 to ensure this
    // node is only left or right node 
    // of its parent node.
    sum[i] = -1;
    
    // Variables for finding left node.
    int leftIndex = -1;
    int leftMaxi = -1;
    
    // Traverse through all successor nodes and 
    // set left index to index with maximum number
    // of successor nodes.
    for (int j = 0; j < mat.Count; j++) {
        
        if (mat[i][j] == 1 && sum[j] > leftMaxi) {
            leftMaxi = sum[j];
            leftIndex = j;
        }
    }
    
    // If there is at least one value, then create 
    // left subtree.
    if (leftIndex != -1) 
        root.left = constructTree(leftIndex, mat, sum);
    
    // Variables for right subtree.
    int rightIndex = -1;
    int rightMaxi = -1;
    
    // Traverse through all successor nodes and 
    // set right index to index with maximum number
    // of successor nodes. (Note: All the left subtree 
    // nodes will have -1 as value here).
    for (int j = 0; j < mat.Count; j++) {
        if (mat[i][j] == 1 && sum[j] > rightMaxi) {
            rightMaxi = sum[j];
            rightIndex = j;
        }
    }
    
    // If right subtree exists.
    if (rightIndex != -1)
        root.right = constructTree(rightIndex, mat, sum);
    
    return root;
}

static Node ancestorTree(List<List<int>> mat) {
    int n = mat.Count;
    
    // Array to store number of 
    // successor nodes for each node.
    List<int> sum = new List<int>(new int[n]);
    
    int rootIndex = -1;
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            sum[i] += mat[i][j];
        }
        
        // If sum[i] is equal to (n-1),
        // then it is the root node.
        if (sum[i] == n - 1)
            rootIndex = i;
    }
    
    Node root = constructTree(rootIndex, mat, sum);
    
    return root;
}

static void printInorder(Node node) {
    if (node == null)
        return;
    printInorder(node.left);
    Console.Write(node.data + " ");
    printInorder(node.right);
}

static void Main(string[] args) {
    List<List<int>> mat = new List<List<int>> {
        new List<int> { 0, 0, 0, 0, 0, 0 },
        new List<int> { 1, 0, 0, 0, 1, 0 },
        new List<int> { 0, 0, 0, 1, 0, 0 },
        new List<int> { 0, 0, 0, 0, 0, 0 },
        new List<int> { 0, 0, 0, 0, 0, 0 },
        new List<int> { 1, 1, 1, 1, 1, 0 }
    };
    
    Node root = ancestorTree(mat);
    
    printInorder(root);
}

}

JavaScript

// JavaScript program to construct binary // tree from ancestor matrix.

class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } }

function constructTree(i, mat, sum) {

// Create current node.
let root = new Node(i);

// Set sum[i] to -1 to ensure this
// node is only left or right node 
// of its parent node.
sum[i] = -1;

// Variables for finding left node.
let leftIndex = -1;
let leftMaxi = -1;

// Traverse through all successor nodes and 
// set left index to index with maximum number
// of successor nodes.
for (let j = 0; j < mat.length; j++) {
    
    if (mat[i][j] === 1 && sum[j] > leftMaxi) {
        leftMaxi = sum[j];
        leftIndex = j;
    }
}

// If there is at least one value, then create 
// left subtree.
if (leftIndex !== -1) 
    root.left = constructTree(leftIndex, mat, sum);

// Variables for right subtree.
let rightIndex = -1;
let rightMaxi = -1;

// Traverse through all successor nodes and 
// set right index to index with maximum number
// of successor nodes. (Note: All the left subtree 
// nodes will have -1 as value here).
for (let j = 0; j < mat.length; j++) {
    if (mat[i][j] === 1 && sum[j] > rightMaxi) {
        rightMaxi = sum[j];
        rightIndex = j;
    }
}

// If right subtree exists.
if (rightIndex !== -1)
    root.right = constructTree(rightIndex, mat, sum);

return root;

}

function ancestorTree(mat) { let n = mat.length;

// Array to store number of 
// successor nodes for each node.
let sum = Array(n).fill(0);

let rootIndex = -1;

for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
        sum[i] += mat[i][j];
    }
    
    // If sum[i] is equal to (n-1),
    // then it is the root node.
    if (sum[i] === n - 1)
        rootIndex = i;
}

let root = constructTree(rootIndex, mat, sum);

return root;

}

function printInorder(node) { if (node === null) return; printInorder(node.left); console.log(node.data + " "); printInorder(node.right); }

let 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] ];

let root = ancestorTree(mat);

printInorder(root);

`

**Time Complexity: O(n^2), where **n is the size of the binary tree.
**Auxiliary Space: O(n)

Please refer to this article for **Bottom-Up approach: Construct tree from ancestor matrix.