//here is a simple program that will create a binary search tree and traverse it.
#include<iostream>
#include<conio.h>
using namespace std;
class bst
{
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
tree *root;
public:
bst()
{
root=NULL;
}
bool IsEmpty()const
{
return root == NULL;
}
void insert(int num)
{
tree *temp,*parent;
temp=new tree;
temp->data=num;
temp->left=NULL;
temp->right=NULL;
parent=NULL;
if(IsEmpty())
{
root=temp;
return;
}
else
{
tree *curr;
curr=root;
while(curr)
{
parent=curr;
if(temp->data>curr->data)
curr=curr->right;
else
curr=curr->left;
}
if(temp->data>parent->data)
parent->right=temp;
else
parent->left=temp;
}
return;
}
void inorder_traverse()
{
this->inorder(root);
}
void inorder(tree *p)
{
if(p->left)
inorder(p->left);
cout<<p->data<<" ";
if(p->right)
inorder(p->right);
}
void preorder_traverse()
{
this->preorder(root);
}
void preorder(tree *p)
{
cout<<p->data<<" ";
if(p->left)
preorder(p->left);
if(p->right)
preorder(p->right);
}
void postorder_traverse()
{
this->postorder(root);
}
void postorder(tree *p)
{
if(p->left)
postorder(p->left);
if(p->right)
postorder(p->right);
cout<<p->data<<" ";
}
};
int main()
{
bst b;
b.insert(10);
b.insert(15);
b.insert(5);
b.inorder_traverse();
cout<<endl;
b.preorder_traverse();
cout<<endl;
b.postorder_traverse();
cout<<endl;
return 0;
}
No comments:
Post a Comment