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.
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.
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:
The rows that correspond to leaves have all 0's
The row that corresponds to root has maximum number of 1's.
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:
C++
// C++ program to construct binary // tree from ancestor matrix.#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Constructs tree from ancestor matrix Node*ancestorTree(vector<vector<int>>mat){intn=mat.size();// Binary array to determine whether // parent is set for node i or not vector<bool>parent(n,false);// Root will store the root of the constructed tree Node*root=nullptr;// Create a map, sum is used as key and row // numbers are used as values map<int,vector<int>>map;for(inti=0;i<n;i++){intsum=0;for(intj=0;j<n;j++)sum+=mat[i][j];// insert(sum, i) pairs into the map map[sum].push_back(i);}// node[i] will store node for i in constructed tree vector<Node*>node(n,nullptr);// Traverse all entries of map. Note that values // are accessed in increasing order of sum for(autopair:map){vector<int>values=pair.second;for(autoval:values){node[val]=newNode(val);// To store last processed node. This node will be // root after loop terminates root=node[val];// For all successor nodes, check // if their parent node is set.for(inti=0;i<n;i++){// if parent is not set and ancestor exists if(mat[val][i]==1&&parent[i]==false){// check for unoccupied left/right node // and set parent of node i if(node[val]->left==nullptr)node[val]->left=node[i];elsenode[val]->right=node[i];parent[i]=true;}}}}returnroot;}voidprintInorder(Node*node){if(node==nullptr)return;printInorder(node->left);cout<<node->data<<" ";printInorder(node->right);}intmain(){vector<vector<int>>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);return0;}
Java
// Java program to construct binary // tree from ancestor matrix.importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Constructs tree from ancestor matrix staticNodeancestorTree(ArrayList<ArrayList<Integer>>mat){intn=mat.size();// Binary array to determine whether // parent is set for node i or not ArrayList<Boolean>parent=newArrayList<>(n);for(inti=0;i<n;i++)parent.add(false);// Root will store the root of the constructed tree Noderoot=null;// Create a map, sum is used as key and row // numbers are used as values Map<Integer,ArrayList<Integer>>map=newTreeMap<>();for(inti=0;i<n;i++){intsum=0;for(intj=0;j<n;j++)sum+=mat.get(i).get(j);// insert(sum, i) pairs into the map map.computeIfAbsent(sum,k->newArrayList<>()).add(i);}// node[i] will store node for i in constructed tree ArrayList<Node>node=newArrayList<>(n);for(inti=0;i<n;i++)node.add(null);// Traverse all entries of map. Note that values // are accessed in increasing order of sum for(Map.Entry<Integer,ArrayList<Integer>>pair:map.entrySet()){ArrayList<Integer>values=pair.getValue();for(intval:values){node.set(val,newNode(val));// To store last processed node. This node will be // root after loop terminates root=node.get(val);// For all successor nodes, check // if their parent node is set.for(inti=0;i<n;i++){// if parent is not set and ancestor exists if(mat.get(val).get(i)==1&&!parent.get(i)){// check for unoccupied left/right node // and set parent of node i if(node.get(val).left==null)node.get(val).left=node.get(i);elsenode.get(val).right=node.get(i);parent.set(i,true);}}}}returnroot;}staticvoidprintInorder(Nodenode){if(node==null)return;printInorder(node.left);System.out.print(node.data+" ");printInorder(node.right);}publicstaticvoidmain(String[]args){ArrayList<ArrayList<Integer>>mat=newArrayList<>();mat.add(newArrayList<>(List.of(0,0,0,0,0,0)));mat.add(newArrayList<>(List.of(1,0,0,0,1,0)));mat.add(newArrayList<>(List.of(0,0,0,1,0,0)));mat.add(newArrayList<>(List.of(0,0,0,0,0,0)));mat.add(newArrayList<>(List.of(0,0,0,0,0,0)));mat.add(newArrayList<>(List.of(1,1,1,1,1,0)));Noderoot=ancestorTree(mat);printInorder(root);}}
Python
# Python program to construct binary # tree from ancestor matrix.classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Constructs tree from ancestor matrix defancestorTree(mat):n=len(mat)# Binary array to determine whether # parent is set for node i or not parent=[False]*n# Root will store the root of the # constructed tree root=None# Create a map, sum is used as key and row # numbers are used as values my_map={}foriinrange(n):sum_val=sum(mat[i])# insert(sum, i) pairs into the map ifsum_valnotinmy_map:my_map[sum_val]=[]my_map[sum_val].append(i)# node[i] will store node for i in# constructed tree node=[None]*n# Traverse all entries of map. Note that values # are accessed in increasing order of sum forkeyinsorted(my_map.keys()):forvalinmy_map[key]:node[val]=Node(val)# To store last processed node. This node will be # root after loop terminates root=node[val]# For all successor nodes, check # if their parent node is set.foriinrange(n):# if parent is not set and ancestor exists ifmat[val][i]==1andnotparent[i]:# check for unoccupied left/right node # and set parent of node i ifnode[val].leftisNone:node[val].left=node[i]else:node[val].right=node[i]parent[i]=TruereturnrootdefprintInorder(node):ifnodeisNone:returnprintInorder(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.usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Constructs tree from ancestor matrixstaticNodeancestorTree(List<List<int>>mat){intn=mat.Count;// Binary array to determine whether // parent is set for node i or not List<bool>parent=newList<bool>(newbool[n]);// Root will store the root of the constructed tree Noderoot=null;// Create a map, sum is used as key and row // numbers are used as values SortedDictionary<int,List<int>>map=newSortedDictionary<int,List<int>>();for(inti=0;i<n;i++){intsum=0;for(intj=0;j<n;j++)sum+=mat[i][j];// insert(sum, i) pairs into the map if(!map.ContainsKey(sum))map[sum]=newList<int>();map[sum].Add(i);}// node[i] will store node for i in constructed tree List<Node>node=newList<Node>(newNode[n]);// Traverse all entries of map. Note that values // are accessed in increasing order of sum foreach(varpairinmap){List<int>values=pair.Value;foreach(intvalinvalues){node[val]=newNode(val);// To store last processed node. This node will be // root after loop terminates root=node[val];// For all successor nodes, check // if their parent node is set.for(inti=0;i<n;i++){// if parent is not set and ancestor exists if(mat[val][i]==1&&!parent[i]){// check for unoccupied left/right node // and set parent of node i if(node[val].left==null)node[val].left=node[i];elsenode[val].right=node[i];parent[i]=true;}}}}returnroot;}staticvoidprintInorder(Nodenode){if(node==null)return;printInorder(node.left);Console.Write(node.data+" ");printInorder(node.right);}staticvoidMain(string[]args){List<List<int>>mat=newList<List<int>>{newList<int>{0,0,0,0,0,0},newList<int>{1,0,0,0,1,0},newList<int>{0,0,0,1,0,0},newList<int>{0,0,0,0,0,0},newList<int>{0,0,0,0,0,0},newList<int>{1,1,1,1,1,0}};Noderoot=ancestorTree(mat);printInorder(root);}}
JavaScript
// JavaScript program to construct binary // tree from ancestor matrix.classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Constructs tree from ancestor matrix functionancestorTree(mat){constn=mat.length;// Binary array to determine whether // parent is set for node i or not constparent=Array(n).fill(false);// Root will store the root of the// constructed tree letroot=null;// Create a map, sum is used as key and row // numbers are used as values constmap=newMap();for(leti=0;i<n;i++){letsum=0;for(letj=0;j<n;j++)sum+=mat[i][j];// insert(sum, i) pairs into the map if(!map.has(sum)){map.set(sum,[]);}map.get(sum).push(i);}// node[i] will store node for i in constructed tree constnode=Array(n).fill(null);// Traverse all entries of map. Note that values // are accessed in increasing order of sum for(const[key,values]of[...map.entries()].sort((a,b)=>a[0]-b[0])){for(constvalofvalues){node[val]=newNode(val);// To store last processed node. This node will be // root after loop terminates root=node[val];// For all successor nodes, check // if their parent node is set.for(leti=0;i<n;i++){// if parent is not set and ancestor exists if(mat[val][i]===1&&parent[i]===false){// check for unoccupied left/right node // and set parent of node i if(node[val].left===null)node[val].left=node[i];elsenode[val].right=node[i];parent[i]=true;}}}}returnroot;}functionprintInorder(node){if(node===null)return;printInorder(node.left);process.stdout.write(node.data+" ");printInorder(node.right);}constmat=[[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]];constroot=ancestorTree(mat);printInorder(root);
Output
0 1 4 5 3 2
Time Complexity: O(n^2), wheren is the number of nodes in the tree. Auxiliary Space: O(n)