The binary tree is a fundamental data structure used in computer science. The binary tree is a useful data structure for rapidly storing sorted data and rapidly retrieving stored data. A binary tree is composed of parent nodes, or leaves, each of which stores data and also links to up to two other child nodes (leaves) which can be visualized spatially as below the first node with one placed to the left and with one placed to the right. It is the relationship between the leaves linked to and the linking leaf, also known as the parent node, which makes the binary tree such an efficient data structure. It is the leaf on the left which has a lesser key value (i.e., the value used to search for a leaf in the tree), and it is the leaf on the right which has an equal or greater key value. As a result, the leaves on the farthest left of the tree have the lowest values, whereas the leaves on the right of the tree have the greatest values. More importantly, as each leaf connects to two other leaves, it is the beginning of a new, smaller, binary tree. Due to this nature, it is possible to easily access and insert data in a binary tree using search and insert functions recursively called on successive leaves.
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
struct btree
{
char data;
btree* lchild;
btree* rchild;
};
btree* bcreate(btree* t,char k);
void show(btree *t,int n);
int hgt(btree* t);
int main()
{
btree *p=NULL;
char c,d; int l,k=0;
cout<<"enter data\n";
cin>>c;
p=bcreate(p,c);
cout<<endl;
l=hgt(p);
while(k<=l)
{
show(p,k++);
cout<<endl;
}
return 0;
}
btree* bcreate(btree* t,char k)
{
btree *s=NULL,*r=NULL;char c1,c2;
if(t==NULL && k!='.')
{
t=new(btree);
t->data=k;
t->rchild=NULL; t->lchild=NULL;
cout<<"enter left and right child of "<<k<<endl;
cin>>c1>>c2;
t->lchild=bcreate(s,c1);
t->rchild=bcreate(r,c2);
return t;
}
return t;
}
int hgt(btree* t)
{
if(t==NULL)
return -1;
else
{
int a=hgt(t->lchild);
int b=hgt(t->rchild);
if(a>b)
return a+1;
else
return b+1;
}
}
void show(btree *t,int n)
{
if(n==0 && t!=NULL)
cout<<t->data<<" ";
else
{
show(t->lchild,n-1);
show(t->rchild,n-1);
}
}
No comments:
Post a Comment