BST tree in C++
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node *root,*nptr,*tptr;
Node *createNode(int value)
{
Node *newNode=new Node;
newNode->data=value;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
void link(Node *ptr)
{
if(root==NULL)
{
root=ptr;
}
else
{
tptr=root;
while(true)
{
if(tptr->data<ptr->data)
{
if(tptr->right==NULL)
{
tptr->right=ptr;
break;
}
else
{
tptr=tptr->right;
}
}
else
{
if(tptr->left==NULL)
{
tptr->left=ptr;
break;
}
else
{
tptr=tptr->left;
}
}
}
}
}
void inorder(Node *nptr)
{
if(nptr!=NULL)
{
inorder(nptr->left);
cout<<nptr->data<< " ";
inorder(nptr->right);
}
}
void postorder(Node *nptr)
{
if(nptr!=NULL)
{
inorder(nptr->left);
inorder(nptr->right);
cout<<nptr->data<< " ";
}
}
void preorder(Node *nptr)
{
if(nptr!=NULL)
{
cout<<nptr->data<< " ";
inorder(nptr->left);
inorder(nptr->right);
}
}
int main()
{
root=NULL;
Node *curr;
curr=createNode(40);
link(curr);
curr=createNode(10);
link(curr);
curr=createNode(20);
link(curr);
curr=createNode(60);
link(curr);
curr=createNode(50);
link(curr);
inorder(root);
return 0;
}
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node *root,*nptr,*tptr;
Node *createNode(int value)
{
Node *newNode=new Node;
newNode->data=value;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
void link(Node *ptr)
{
if(root==NULL)
{
root=ptr;
}
else
{
tptr=root;
while(true)
{
if(tptr->data<ptr->data)
{
if(tptr->right==NULL)
{
tptr->right=ptr;
break;
}
else
{
tptr=tptr->right;
}
}
else
{
if(tptr->left==NULL)
{
tptr->left=ptr;
break;
}
else
{
tptr=tptr->left;
}
}
}
}
}
void inorder(Node *nptr)
{
if(nptr!=NULL)
{
inorder(nptr->left);
cout<<nptr->data<< " ";
inorder(nptr->right);
}
}
void postorder(Node *nptr)
{
if(nptr!=NULL)
{
inorder(nptr->left);
inorder(nptr->right);
cout<<nptr->data<< " ";
}
}
void preorder(Node *nptr)
{
if(nptr!=NULL)
{
cout<<nptr->data<< " ";
inorder(nptr->left);
inorder(nptr->right);
}
}
int main()
{
root=NULL;
Node *curr;
curr=createNode(40);
link(curr);
curr=createNode(10);
link(curr);
curr=createNode(20);
link(curr);
curr=createNode(60);
link(curr);
curr=createNode(50);
link(curr);
inorder(root);
return 0;
}
No comments