Generic Trees implementation in C/C++
Why Tree?
Unlike Array and Linked List, which are linear data structures, tree is hierarchical (or non-linear) data structure.
Unlike Array and Linked List, which are linear data structures, tree is hierarchical (or non-linear) data structure.
One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer:
So lets get started with trees
So lets get started with trees
First of all lets see a tree data structure in a general form later on we would see specific Trees like Binary Tree, Binary Search Tree, AVL Trees etc.
A Tree is a Non-linear data structure, in which there is Parent node and that parent node has any No. of children
A Tree is a Non-linear data structure, in which there is Parent node and that parent node has any No. of children
now lets see a program:-
The following Program includes Build Tree function, Max Depth, Max Element and Print(BFS) function
#include<iostream>
#include<queue>
using namespace std;
struct node{
int data;
int childcount;
node **child;
};
node *BuildTree(){
node *root=new node;
cout<<"enter the data of root\t";
cin>>root->data;
queue <node *> q;
q.push(root);
while(!q.empty()){
node *temp=q.front();
cout<<"\nenter no of childs of node whith data "<<temp->data << endl;
cin>>temp->childcount;
temp->child=new node*[temp->childcount];
for(int i=0;i<temp->childcount;i++){
temp->child[i]=new node;
cout<<"\nEnter data ";
cin >> temp->child[i]->data;
q.push(temp->child[i]);
}
q.pop();
}
return root;
}
void printTree(node *root){
node* temp=root;
queue <node *> q;
q.push(root);
while(!q.empty()){
node *temp=q.front();
cout<<"\nnode whith data "<<temp->data << " Has "<<temp->childcount << " childern"<<endl;
for(int i=0;i<temp->childcount;i++){
node *c;
c=temp->child[i];
q.push(c);
}
cout <<"\n";
q.pop();
}
}
int max_element(node *root){
queue <node *> q;
q.push(root);
int max=root->data;
while(!q.empty()){
node *temp=q.front();
if(temp->data>max){
max=temp->data;
}
for(int i=0;i<temp->childcount;i++){
node *c;
c=temp->child[i];
q.push(c);
}
q.pop();
}
return max;
}
int max_depth(node *root){
if(root->childcount==0){
return 0;
}
int depth=-1,tempDepth;
for(int i=0;i<root->childcount;i++){
tempDepth = max_depth(root->child[i]);
if(depth<tempDepth){
depth=tempDepth;
}
}
return depth+1;
}
main(){
node *root=BuildTree();
printTree(root);
int depth=max_depth(root);
cout<<"\nDepth is "<<depth;
cout<<"\nMax element is = "<<max_element(root);
}
No comments:
Post a Comment