Note : No global declarations.
Consider following Binary Tree
root=50
root->left=17
root->left->left=12
root->left->left->left=9
root->left->left->right=14
root->left->right=23
root->left->right->right=19
root->right-=72
root->right->right=76
root->right->left=54
root->right->left->right=67
Your task is to write its array representation.
#include<iostream>
using namespace std;
int br_tree[10];
void root(int k) {
if (br_tree[0] != '\0')
cout << "Tree already had root";
else
br_tree[0] = k;
}
void setLeft(int k, int p) {
if (br_tree[p] == '\0')
cout << "\nCan't set child at"
<< (p * 2) + 1
<< " , no parent found";
else
br_tree[(p * 2) + 1] = k;
}
void setRight(int k, int p) {
if (br_tree[p] == '\0')
cout << "\nCan't set child at"
<< (p * 2) + 2
<< " , no parent found";
else
br_tree[(p * 2) + 2] = k;
}
void display() {
cout << "\n";
for (int i = 0; i < 10; i++) {
if (br_tree[i] != '\0')
cout << br_tree[i]<<" ";
else
cout << "-";
}
}
int main() {
root(50);
setLeft(17, 0);
setLeft(12, 1);
setLeft(9, 2);
setRight(14, 0);
setRight(23, 1);
setRight(19, 2);
setRight(72, 3);
setRight(76, 4);
setLeft(54, 3);
setRight(67, 5);
display();
return 0;
}
Comments
Leave a comment