Tree Implementation
Tree can be implemented in 2 ways;
- Tree implementation Using Link List in C++
- Tree implementation Using Arrays in C++
C++ Program to implement Tree with Arrays
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 |
#include<bits/stdc++.h> using namespace std; char Tree_T4Tutorials[8]; int root(char key) { if (Tree_T4Tutorials[0] != '\0') cout << "Tree already had root"; else Tree_T4Tutorials[0] = key; return 0; } int Setting_Left_Values(char key, int Parent_Node) { if (Tree_T4Tutorials[Parent_Node] == '\0') cout << "\n Sorry! Program Can't set child at: "<< (Parent_Node * 2) + 1 << " , Sorry! no Parent_Node found in the program"<<endl; else Tree_T4Tutorials[(Parent_Node * 2) + 1] = key; return 0; } int Setting_Right_Values(char key, int Parent_Node) { if (Tree_T4Tutorials[Parent_Node] == '\0') cout << "\n Sorry! Program Can't set child at" << (Parent_Node * 2) + 2 << " , Sorry! no Parent_Node found in the program"<<endl; else Tree_T4Tutorials[(Parent_Node * 2) + 2] = key; return 0; } int Display() { cout << "\n"; for (int i = 0; i < 8; i++) { if (Tree_T4Tutorials[i] != '\0') cout << Tree_T4Tutorials[i]; else cout << "-"; } return 0; } // Driver Code int main() { root('M'); //insert_left('N',0); Setting_Right_Values('O', 0); Setting_Left_Values('P', 1); Setting_Right_Values('Q', 1); Setting_Right_Values('R', 2); Display(); return 0; } |
Output
Sorry! Program Can’t set child at:Â 3 Sorry! no Parent_Node found in the program
Sorry! Program Can’t set child at:Â 4 Sorry! no Parent_Node found in the program
M – O — R –