/* Height/Depth of a Tree */
#include<iostream.h>
#include<alloc.h>
#include<conio.h>
struct tree
{
int item,level;
struct tree *right,*left;
};
void create(struct tree *p)
{
int choice;
cout<<"\nEnter value";
cin>>p->item;
cout<<"\nDo you Want to Enter left Child of "<<p->item<<" .1.YES/2.NO";
cin>>choice;
if(choice==1)
{
p->left=(tree*)malloc(sizeof(tree));
p->left->level=p->level+1;
create(p->left);
}
else
{
p->left=NULL;
}
cout<<"Do you Want to Enter Right Child of "<<p->item<<" .1.YES/2.NO";
cin>>choice;
if(choice==1)
{
p->right=(tree*)malloc(sizeof(tree));
p->right->level=p->level+1;
create(p->right);
}
else
{
p->right=NULL;
}
}
static int max=0;
void findmax(tree *p)
{
if(p==NULL)return;
if(p->level>max)
max=p->level;
findmax(p->left);
findmax(p->right);
}
int main()
{
clrscr();
struct tree *a;
a=(tree*)malloc(sizeof(tree));
a->level=0;
cout<<"Enter Tree\n";
create(a);
findmax(a);
cout<<"\nHeight of a Binary Tree is"<<max;
getch();
return 0;
}
#include<iostream.h>
#include<alloc.h>
#include<conio.h>
struct tree
{
int item,level;
struct tree *right,*left;
};
void create(struct tree *p)
{
int choice;
cout<<"\nEnter value";
cin>>p->item;
cout<<"\nDo you Want to Enter left Child of "<<p->item<<" .1.YES/2.NO";
cin>>choice;
if(choice==1)
{
p->left=(tree*)malloc(sizeof(tree));
p->left->level=p->level+1;
create(p->left);
}
else
{
p->left=NULL;
}
cout<<"Do you Want to Enter Right Child of "<<p->item<<" .1.YES/2.NO";
cin>>choice;
if(choice==1)
{
p->right=(tree*)malloc(sizeof(tree));
p->right->level=p->level+1;
create(p->right);
}
else
{
p->right=NULL;
}
}
static int max=0;
void findmax(tree *p)
{
if(p==NULL)return;
if(p->level>max)
max=p->level;
findmax(p->left);
findmax(p->right);
}
int main()
{
clrscr();
struct tree *a;
a=(tree*)malloc(sizeof(tree));
a->level=0;
cout<<"Enter Tree\n";
create(a);
findmax(a);
cout<<"\nHeight of a Binary Tree is"<<max;
getch();
return 0;
}
No comments:
Post a Comment