[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:
C++
// C++ program Construct Ancestor Matrix// from a Given Binary Tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Count number of nodes in tree.intnodeCount(Node*root){if(root==nullptr)return0;returnnodeCount(root->left)+nodeCount(root->right)+1;}// Recursive function to fill ancestor matrix.voidancestorMatrixRecur(Node*root,vector<vector<int>>&mat,vector<int>&anc){if(root==nullptr)return;intcurr=root->data;// Set ancestor valuesfor(inti=0;i<anc.size();i++){mat[anc[i]][curr]=1;}// Push the current node into anc.anc.push_back(curr);// Process left and right subtree.ancestorMatrixRecur(root->left,mat,anc);ancestorMatrixRecur(root->right,mat,anc);// Pop the current node from anc.anc.pop_back();}// Function to construct ancestor matrix.vector<vector<int>>ancestorMatrix(Node*root){if(root==nullptr)return{{}};intn=nodeCount(root);vector<vector<int>>mat(n,vector<int>(n,0));// vector to store ancestor along all paths.vector<int>anc;ancestorMatrixRecur(root,mat,anc);returnmat;}intmain(){// Construct the following binary tree// 5// / \ // 1 2// / \ /// 0 4 3 Node*root=newNode(5);root->left=newNode(1);root->right=newNode(2);root->left->left=newNode(0);root->left->right=newNode(4);root->right->left=newNode(3);vector<vector<int>>mat=ancestorMatrix(root);for(inti=0;i<mat.size();i++){for(intj=0;j<mat[i].size();j++){cout<<mat[i][j]<<" ";}cout<<endl;}return0;}
Java
// Java program Construct Ancestor Matrix// from a Given Binary Treeimportjava.util.ArrayList;importjava.util.List;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Count number of nodes in tree.staticintnodeCount(Noderoot){if(root==null)return0;returnnodeCount(root.left)+nodeCount(root.right)+1;}// Recursive function to fill ancestor matrix.staticvoidancestorMatrixRecur(Noderoot,List<List<Integer>>mat,List<Integer>anc){if(root==null)return;intcurr=root.data;// Set ancestor valuesfor(inti=0;i<anc.size();i++){mat.get(anc.get(i)).set(curr,1);}// Push the current node into anc.anc.add(curr);// Process left and right subtree.ancestorMatrixRecur(root.left,mat,anc);ancestorMatrixRecur(root.right,mat,anc);// Pop the current node from anc.anc.remove(anc.size()-1);}// Function to construct ancestor matrix.staticList<List<Integer>>ancestorMatrix(Noderoot){if(root==null)returnnewArrayList<>();intn=nodeCount(root);List<List<Integer>>mat=newArrayList<>();for(inti=0;i<n;i++){List<Integer>row=newArrayList<>();for(intj=0;j<n;j++){row.add(0);}mat.add(row);}// List to store ancestor along all paths.List<Integer>anc=newArrayList<>();ancestorMatrixRecur(root,mat,anc);returnmat;}publicstaticvoidmain(String[]args){// Construct the following binary tree// 5// / \// 1 2// / \ /// 0 4 3 Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(0);root.left.right=newNode(4);root.right.left=newNode(3);List<List<Integer>>mat=ancestorMatrix(root);for(List<Integer>row:mat){for(intval:row){System.out.print(val+" ");}System.out.println();}}}
Python
# Python program Construct Ancestor Matrix# from a Given Binary TreeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Count number of nodes in tree.defnodeCount(root):ifrootisNone:return0returnnodeCount(root.left)+nodeCount(root.right)+1# Recursive function to fill ancestor matrix.defancestorMatrixRecur(root,mat,anc):ifrootisNone:returncurr=root.data# Set ancestor valuesforiinrange(len(anc)):mat[anc[i]][curr]=1# Push the current node into anc.anc.append(curr)# Process left and right subtree.ancestorMatrixRecur(root.left,mat,anc)ancestorMatrixRecur(root.right,mat,anc)# Pop the current node from anc.anc.pop()# Function to construct ancestor matrix.defancestorMatrix(root):ifrootisNone:return[]n=nodeCount(root)mat=[[0for_inrange(n)]for_inrange(n)]# List to store ancestor along all paths.anc=[]ancestorMatrixRecur(root,mat,anc)returnmatif__name__=="__main__":# Construct the following binary tree# 5# / \# 1 2# / \ /# 0 4 3 root=Node(5)root.left=Node(1)root.right=Node(2)root.left.left=Node(0)root.left.right=Node(4)root.right.left=Node(3)mat=ancestorMatrix(root)forrowinmat:print(" ".join(map(str,row)))
C#
// C# program Construct Ancestor Matrix// from a Given Binary TreeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Count number of nodes in tree.staticintnodeCount(Noderoot){if(root==null)return0;returnnodeCount(root.left)+nodeCount(root.right)+1;}// Recursive function to fill ancestor matrix.staticvoidancestorMatrixRecur(Noderoot,List<List<int>>mat,List<int>anc){if(root==null)return;intcurr=root.data;// Set ancestor valuesfor(inti=0;i<anc.Count;i++){mat[anc[i]][curr]=1;}// Push the current node into anc.anc.Add(curr);// Process left and right subtree.ancestorMatrixRecur(root.left,mat,anc);ancestorMatrixRecur(root.right,mat,anc);// Pop the current node from anc.anc.RemoveAt(anc.Count-1);}// Function to construct ancestor matrix.staticList<List<int>>ancestorMatrix(Noderoot){if(root==null)returnnewList<List<int>>();intn=nodeCount(root);List<List<int>>mat=newList<List<int>>();for(inti=0;i<n;i++){List<int>row=newList<int>();for(intj=0;j<n;j++){row.Add(0);}mat.Add(row);}// List to store ancestor along all paths.List<int>anc=newList<int>();ancestorMatrixRecur(root,mat,anc);returnmat;}staticvoidMain(string[]args){// Construct the following binary tree// 5// / \// 1 2// / \ /// 0 4 3 Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(0);root.left.right=newNode(4);root.right.left=newNode(3);List<List<int>>mat=ancestorMatrix(root);foreach(List<int>rowinmat){foreach(intvalinrow){Console.Write(val+" ");}Console.WriteLine();}}}
JavaScript
// Javascript program Construct Ancestor Matrix// from a Given Binary TreeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Count number of nodes in tree.functionnodeCount(root){if(root===null)return0;returnnodeCount(root.left)+nodeCount(root.right)+1;}// Recursive function to fill ancestor matrix.functionancestorMatrixRecur(root,mat,anc){if(root===null)return;constcurr=root.data;// Set ancestor valuesfor(leti=0;i<anc.length;i++){mat[anc[i]][curr]=1;}// Push the current node into anc.anc.push(curr);// Process left and right subtree.ancestorMatrixRecur(root.left,mat,anc);ancestorMatrixRecur(root.right,mat,anc);// Pop the current node from anc.anc.pop();}// Function to construct ancestor matrix.functionancestorMatrix(root){if(root===null)return[];constn=nodeCount(root);constmat=Array.from({length:n},()=>Array(n).fill(0));// List to store ancestor along all paths.constanc=[];ancestorMatrixRecur(root,mat,anc);returnmat;}// Construct the following binary tree// 5// / \// 1 2// / \ /// 0 4 3 constroot=newNode(5);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(0);root.left.right=newNode(4);root.right.left=newNode(3);constmat=ancestorMatrix(root);mat.forEach(row=>{console.log(row.join(" "));});
[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:
C++
// C++ program Construct Ancestor Matrix// from a Given Binary Tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Count number of nodes in tree.intnodeCount(Node*root){if(root==nullptr)return0;returnnodeCount(root->left)+nodeCount(root->right)+1;}// Recursive function to fill ancestor matrix.voidancestorMatrixRecur(Node*root,vector<vector<int>>&mat){intcurr=root->data;if(root->left!=nullptr){intleft=root->left->data;// Process the left subtree.ancestorMatrixRecur(root->left,mat);// Set curr node as ancestor of nodes// for which left node is also ancestor.for(intj=0;j<mat.size();j++){if(mat[left][j]==1)mat[curr][j]=1;}// Set curr node as ancestor of left // node.mat[curr][left]=1;}if(root->right!=nullptr){intright=root->right->data;// Process the right subtree.ancestorMatrixRecur(root->right,mat);// Set curr node as ancestor of nodes// for which right node is also ancestor.for(intj=0;j<mat.size();j++){if(mat[right][j]==1)mat[curr][j]=1;}// Set curr node as ancestor of right // node.mat[curr][right]=1;}}// Function to construct ancestor matrix.vector<vector<int>>ancestorMatrix(Node*root){if(root==nullptr)return{{}};intn=nodeCount(root);vector<vector<int>>mat(n,vector<int>(n,0));ancestorMatrixRecur(root,mat);returnmat;}intmain(){// Construct the following binary tree// 5// / \ // 1 2// / \ /// 0 4 3 Node*root=newNode(5);root->left=newNode(1);root->right=newNode(2);root->left->left=newNode(0);root->left->right=newNode(4);root->right->left=newNode(3);vector<vector<int>>mat=ancestorMatrix(root);for(inti=0;i<mat.size();i++){for(intj=0;j<mat[i].size();j++){cout<<mat[i][j]<<" ";}cout<<endl;}return0;}
Java
// Java program Construct Ancestor Matrix// from a Given Binary Treeimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Count number of nodes in tree.staticintnodeCount(Noderoot){if(root==null)return0;returnnodeCount(root.left)+nodeCount(root.right)+1;}// Recursive function to fill ancestor matrix.staticvoidancestorMatrixRecur(Noderoot,ArrayList<ArrayList<Integer>>mat){intcurr=root.data;if(root.left!=null){intleft=root.left.data;// Process the left subtree.ancestorMatrixRecur(root.left,mat);// Set curr node as ancestor of nodes// for which left node is also ancestor.for(intj=0;j<mat.size();j++){if(mat.get(left).get(j)==1)mat.get(curr).set(j,1);}// Set curr node as ancestor of left // node.mat.get(curr).set(left,1);}if(root.right!=null){intright=root.right.data;// Process the right subtree.ancestorMatrixRecur(root.right,mat);// Set curr node as ancestor of nodes// for which right node is also ancestor.for(intj=0;j<mat.size();j++){if(mat.get(right).get(j)==1)mat.get(curr).set(j,1);}// Set curr node as ancestor of right // node.mat.get(curr).set(right,1);}}// Function to construct ancestor matrix.staticArrayList<ArrayList<Integer>>ancestorMatrix(Noderoot){if(root==null)returnnewArrayList<>();intn=nodeCount(root);ArrayList<ArrayList<Integer>>mat=newArrayList<>();for(inti=0;i<n;i++){ArrayList<Integer>row=newArrayList<>();for(intj=0;j<n;j++){row.add(0);}mat.add(row);}ancestorMatrixRecur(root,mat);returnmat;}publicstaticvoidmain(String[]args){// Construct the following binary tree// 5// / \// 1 2// / \ /// 0 4 3 Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(0);root.left.right=newNode(4);root.right.left=newNode(3);ArrayList<ArrayList<Integer>>mat=ancestorMatrix(root);for(ArrayList<Integer>row:mat){for(intval:row){System.out.print(val+" ");}System.out.println();}}}
Python
# Python program Construct Ancestor Matrix# from a Given Binary TreeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Count number of nodes in tree.defnodeCount(root):ifrootisNone:return0returnnodeCount(root.left)+nodeCount(root.right)+1# Recursive function to fill ancestor matrix.defancestorMatrixRecur(root,mat):curr=root.dataifroot.leftisnotNone:left=root.left.data# Process the left subtree.ancestorMatrixRecur(root.left,mat)# Set curr node as ancestor of nodes# for which left node is also ancestor.forjinrange(len(mat)):ifmat[left][j]==1:mat[curr][j]=1# Set curr node as ancestor of left # node.mat[curr][left]=1ifroot.rightisnotNone:right=root.right.data# Process the right subtree.ancestorMatrixRecur(root.right,mat)# Set curr node as ancestor of nodes# for which right node is also ancestor.forjinrange(len(mat)):ifmat[right][j]==1:mat[curr][j]=1# Set curr node as ancestor of right # node.mat[curr][right]=1# Function to construct ancestor matrix.defancestorMatrix(root):ifrootisNone:return[[0]]n=nodeCount(root)mat=[[0]*nfor_inrange(n)]ancestorMatrixRecur(root,mat)returnmatif__name__=="__main__":# Construct the following binary tree# 5# / \# 1 2# / \ /# 0 4 3 root=Node(5)root.left=Node(1)root.right=Node(2)root.left.left=Node(0)root.left.right=Node(4)root.right.left=Node(3)mat=ancestorMatrix(root)forrowinmat:print(" ".join(map(str,row)))
C#
// C# program Construct Ancestor Matrix// from a Given Binary TreeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Count number of nodes in tree.staticintnodeCount(Noderoot){if(root==null)return0;returnnodeCount(root.left)+nodeCount(root.right)+1;}// Recursive function to fill ancestor matrix.staticvoidancestorMatrixRecur(Noderoot,List<List<int>>mat){intcurr=root.data;if(root.left!=null){intleft=root.left.data;// Process the left subtree.ancestorMatrixRecur(root.left,mat);// Set curr node as ancestor of nodes// for which left node is also ancestor.for(intj=0;j<mat.Count;j++){if(mat[left][j]==1)mat[curr][j]=1;}// Set curr node as ancestor of left // node.mat[curr][left]=1;}if(root.right!=null){intright=root.right.data;// Process the right subtree.ancestorMatrixRecur(root.right,mat);// Set curr node as ancestor of nodes// for which right node is also ancestor.for(intj=0;j<mat.Count;j++){if(mat[right][j]==1)mat[curr][j]=1;}// Set curr node as ancestor of right // node.mat[curr][right]=1;}}// Function to construct ancestor matrix.staticList<List<int>>ancestorMatrix(Noderoot){if(root==null)returnnewList<List<int>>();intn=nodeCount(root);List<List<int>>mat=newList<List<int>>();for(inti=0;i<n;i++){List<int>row=newList<int>();for(intj=0;j<n;j++){row.Add(0);}mat.Add(row);}ancestorMatrixRecur(root,mat);returnmat;}staticvoidMain(string[]args){// Construct the following binary tree// 5// / \// 1 2// / \ /// 0 4 3 Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(0);root.left.right=newNode(4);root.right.left=newNode(3);List<List<int>>mat=ancestorMatrix(root);foreach(varrowinmat){foreach(varvalinrow){Console.Write(val+" ");}Console.WriteLine();}}}
JavaScript
// Javascript program Construct Ancestor Matrix// from a Given Binary TreeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Count number of nodes in tree.functionnodeCount(root){if(root===null)return0;returnnodeCount(root.left)+nodeCount(root.right)+1;}// Recursive function to fill ancestor matrix.functionancestorMatrixRecur(root,mat){constcurr=root.data;if(root.left!==null){constleft=root.left.data;// Process the left subtree.ancestorMatrixRecur(root.left,mat);// Set curr node as ancestor of nodes// for which left node is also ancestor.for(letj=0;j<mat.length;j++){if(mat[left][j]===1)mat[curr][j]=1;}// Set curr node as ancestor of left // node.mat[curr][left]=1;}if(root.right!==null){constright=root.right.data;// Process the right subtree.ancestorMatrixRecur(root.right,mat);// Set curr node as ancestor of nodes// for which right node is also ancestor.for(letj=0;j<mat.length;j++){if(mat[right][j]===1)mat[curr][j]=1;}// Set curr node as ancestor of right // node.mat[curr][right]=1;}}// Function to construct ancestor matrix.functionancestorMatrix(root){if(root===null)return[[]];constn=nodeCount(root);constmat=Array.from({length:n},()=>Array(n).fill(0));ancestorMatrixRecur(root,mat);returnmat;}// Construct the following binary tree// 5// / \// 1 2// / \ /// 0 4 3 constroot=newNode(5);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(0);root.left.right=newNode(4);root.right.left=newNode(3);constmat=ancestorMatrix(root);for(leti=0;i<mat.length;i++){for(letj=0;j<mat[i].length;j++){process.stdout.write(mat[i][j]+" ");}console.log();}