forked from WaderManasi/Knowing-DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAncestor matrix for binary tree
92 lines (77 loc) · 2.16 KB
/
Ancestor matrix for binary tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// C++ program to construct ancestor matrix for
// given tree.
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
/* A binary tree node */
struct Node
{
int data;
Node *left, *right;
};
// Creating a global boolean matrix for simplicity
bool mat[MAX][MAX];
// anc[] stores all ancestors of current node. This
// function fills ancestors for all nodes.
// It also returns size of tree. Size of tree is
// used to print ancestor matrix.
int ancestorMatrixRec(Node *root, vector<int> &anc)
{
/* base case */
if (root == NULL) return 0;;
// Update all ancestors of current node
int data = root->data;
for (int i=0; i<anc.size(); i++)
mat[anc[i]][data] = true;
// Push data to list of ancestors
anc.push_back(data);
// Traverse left and right subtrees
int l = ancestorMatrixRec(root->left, anc);
int r = ancestorMatrixRec(root->right, anc);
// Remove data from list the list of ancestors
// as all descendants of it are processed now.
anc.pop_back();
return l+r+1;
}
// This function mainly calls ancestorMatrixRec()
void ancestorMatrix(Node *root)
{
// Create an empty ancestor array
vector<int> anc;
// Fill ancestor matrix and find size of
// tree.
int n = ancestorMatrixRec(root, anc);
// Print the filled values
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
/* Helper function to create a new node */
Node* newnode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* Driver program to test above functions*/
int main()
{
/* 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);
ancestorMatrix(root);
return 0;
}