Construct Binary Tree from Ancestor Matrix | Top Down Approach

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 the given ancestor matrix where all its values of nodes are from 0 to n-1.

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

Examples:



Input:
{ {0, 1, 1},
  {0, 0, 0},
  {0, 0, 0}
};
Output:
      0
    /   \
   1     2 

Input:
{ {0, 0, 0, 1, 1, 0},
  {0, 0, 0, 0, 0, 1},
  {1, 1, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0}
};
Output:
          2
        /   \
       0      1
     /   \    /  
    3     4  5

Please refer this article for Bottom Up approach: Construct tree from ancestor matrix

Approach:
First, we will find the root of the tree. The root is the one whose column has all zeros. Once we find the root, we can then construct tree from root using DFS recursive approach.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implemenattion of
// the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Node structure for
// Binary Tree
struct Node {
    int data;
    Node *left, *right;
    Node(int _val)
    {
        data = _val;
        left = right = NULL;
    }
};
  
// Function to return
// root index of a
// binary tree
int getRootIndex(vector<vector<int> >& arr)
{
    int root_index = -1;
  
    for (int j = 0; j < arr[0].size(); j++) {
        int count = 0;
        for (int i = 0; i < arr.size(); i++)
            if (arr[i][j] == 0) {
                count++;
            }
  
        if (count == arr.size()) {
            root_index = j;
            break;
        }
    }
    return root_index;
}
  
// Function to print
// in-order traversal of
// a tree
void printInorder(Node* node)
{
    if (node == NULL) {
        return;
    }
    printInorder(node->left);
    cout << node->data << " ";
    printInorder(node->right);
}
  
// Function to generate binary
// tree from parent matrix
Node* createTreeRec(vector<vector<int> >& arr, int index)
{
  
    Node* node = new Node(index);
  
    // If left is 1 then create
    // left child. (for 1st one in row)
    // If left is 2 then create
    // right child.(for 1st one in row)
    int left = 1;
  
    for (int j = 0; j < arr[index].size(); j++) {
        if (arr[index][j] == 1) {
            // recur for left sub-tree
            if (left == 1) {
                node->left = createTreeRec(arr, j);
            }
            // recur for right sub-tree
            else if (left == 2) {
                node->right = createTreeRec(arr, j);
            }
            left++;
        }
    }
  
    return node;
}
  
// Driver code
int main()
{
  
    // Assuming leftmost 1 in a
    // row is left child, if exists
    // and rightmost 1 in a row
    // is right child, if exists
    vector<vector<int> > arr = {
        { 0, 0, 0, 1, 1, 0 },
        { 0, 0, 0, 0, 0, 1 },
        { 1, 1, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
    };
  
    int root_index = getRootIndex(arr);
    Node* root = createTreeRec(arr, root_index);
  
    // Printing inorder traversal
    // of tree to check the output
    printInorder(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implemenattion of
// the above approach
class GFG
{
  
// Node structure for
// Binary Tree
static class Node
{
    int data;
    Node left, right;
    Node(int _val)
    {
        data = _val;
        left = right = null;
    }
};
  
// Function to return
// root index of a
// binary tree
static int getRootIndex(int [][]arr)
{
    int root_index = -1;
  
    for (int j = 0; j < arr[0].length; j++)
    {
        int count = 0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i][j] == 0)
            {
                count++;
            }
  
        if (count == arr.length)
        {
            root_index = j;
            break;
        }
    }
    return root_index;
}
  
// Function to print
// in-order traversal of
// a tree
static void printInorder(Node node)
{
    if (node == null)
    {
        return;
    }
    printInorder(node.left);
    System.out.print(node.data + " ");
    printInorder(node.right);
}
  
// Function to generate binary
// tree from parent matrix
static Node createTreeRec(int [][]arr, int index)
{
  
    Node node = new Node(index);
  
    // If left is 1 then create
    // left child. (for 1st one in row)
    // If left is 2 then create
    // right child.(for 1st one in row)
    int left = 1;
  
    for (int j = 0; j < arr[index].length; j++) 
    {
        if (arr[index][j] == 1)
        {
            // recur for left sub-tree
            if (left == 1
            {
                node.left = createTreeRec(arr, j);
            }
              
            // recur for right sub-tree
            else if (left == 2)
            {
                node.right = createTreeRec(arr, j);
            }
            left++;
        }
    }
  
    return node;
}
  
// Driver code
public static void main(String[] args)
{
  
    // Assuming leftmost 1 in a
    // row is left child, if exists
    // and rightmost 1 in a row
    // is right child, if exists
    int[][] arr = {
        { 0, 0, 0, 1, 1, 0 },
        { 0, 0, 0, 0, 0, 1 },
        { 1, 1, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
    };
  
    int root_index = getRootIndex(arr);
    Node root = createTreeRec(arr, root_index);
  
    // Printing inorder traversal
    // of tree to check the output
    printInorder(root);
  
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implemenattion of
// the above approach
using System;
  
class GFG
{
  
// Node structure for
// Binary Tree
class Node
{
    public int data;
    public Node left, right;
    public Node(int _val)
    {
        data = _val;
        left = right = null;
    }
};
  
// Function to return
// root index of a
// binary tree
static int getRootIndex(int [,]arr)
{
    int root_index = -1;
  
    for (int j = 0; j < arr.GetLength(0); j++)
    {
        int count = 0;
        for (int i = 0; i < arr.GetLength(1); i++)
            if (arr[i, j] == 0)
            {
                count++;
            }
  
        if (count == arr.GetLength(0))
        {
            root_index = j;
            break;
        }
    }
    return root_index;
}
  
// Function to print
// in-order traversal of
// a tree
static void printInorder(Node node)
{
    if (node == null)
    {
        return;
    }
    printInorder(node.left);
    Console.Write(node.data + " ");
    printInorder(node.right);
}
  
// Function to generate binary
// tree from parent matrix
static Node createTreeRec(int [,]arr, int index)
{
  
    Node node = new Node(index);
  
    // If left is 1 then create
    // left child. (for 1st one in row)
    // If left is 2 then create
    // right child.(for 1st one in row)
    int left = 1;
  
    for (int j = 0; j < arr.GetLength(1); j++) 
    {
        if (arr[index, j] == 1)
        {
            // recur for left sub-tree
            if (left == 1) 
            {
                node.left = createTreeRec(arr, j);
            }
              
            // recur for right sub-tree
            else if (left == 2)
            {
                node.right = createTreeRec(arr, j);
            }
            left++;
        }
    }
  
    return node;
}
  
// Driver code
public static void Main(String[] args)
{
  
    // Assuming leftmost 1 in a
    // row is left child, if exists
    // and rightmost 1 in a row
    // is right child, if exists
    int[,] arr = {
        { 0, 0, 0, 1, 1, 0 },
        { 0, 0, 0, 0, 0, 1 },
        { 1, 1, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
    };
  
    int root_index = getRootIndex(arr);
    Node root = createTreeRec(arr, root_index);
  
    // Printing inorder traversal
    // of tree to check the output
    printInorder(root);
  
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

3 0 4 2 5 1


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rajput-Ji