-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconstruct-ancestor-matrix.cpp
More file actions
executable file
·56 lines (55 loc) · 1.03 KB
/
construct-ancestor-matrix.cpp
File metadata and controls
executable file
·56 lines (55 loc) · 1.03 KB
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
// construct ancestor matrix
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
int mat[50][50];
int mx = -INT_MAX;
node *getnode(int data){
node *temp = new node();
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void form(node *root,int x){
if(!root) return;
//int x = root->data;
mx = max(mx,x);
if(root->left) {
mat[x][root->left->data] = 1;
mx = max(mx,root->left->data);
}
if(root->right){
mat[x][root->right->data] = 1;
mx = max(mx,root->right->data);
}
form(root->left,x);
form(root->right,x);
}
void traverse(node *root){
if(root == NULL) return;
int x = root->data;
form(root,x);
traverse(root->left);
traverse(root->right);
}
int main(){
node *root = getnode(5);
root->left = getnode(1);
root->right = getnode(2);
root->left->left = getnode(0);
root->left->right = getnode(4);
root->right->left = getnode(3);
traverse(root);
for(int i=0;i<=mx;i++){
for(int j=0;j<=mx;j++){
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
return 0;
}