Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//the struct which represents the node
struct tnode {
struct tnode *left, *right;
int key;
};
tnode *insertleft(tnode *tree,int ele)
{
if(tree==NULL)
{
tree=new tnode;
tree->left=tree->right=NULL;
tree->key=ele;
}
else
tree->left=insertleft(tree->left,ele);
return(tree);
}
tnode *insertright(tnode *tree,int ele)
{
if(tree==NULL)
{
tree=new tnode;
tree->left=tree->right=NULL;
tree->key=ele;
}
else
tree->right=insertright(tree->right,ele);
return(tree);
}
void InOrder( tnode *x )
{
if (x == 0) return;
InOrder(x->left);
cout << x->key << " ";
InOrder(x->right);
}
int main (void )
{
srand((long)2004126);
tnode *root = 0;
int size, key2;
int flag;
cout << "\nPlease enter the size of the tree. N: ";
cin >> size;
for (int i = 0; i < size; i++) {
key2 = 1 + rand() % 30000; //creating random node key between 1-30.000
tnode *p = root;
tnode *q = 0;
flag = 0;
//searching existing tree for node with that value
while((p != 0)&&(flag==0)) {
q = p;
if (p->key == key2) {
flag = 1; //node with that key already exists -cant enter
}
else if (p->key < key2) {
p = p->left; //case 1: key smaller than root
}
else {
p = p->right; //case 2: key bigger than root
}
}
//creating new node with key2 as content
if (flag == 0)
{ //flag is 0 when that value didnt already exist on the tree
if (q == 0) {
root =new tnode;
root->left=root->right=NULL;
root->key=key2;
//case of empty tree
//case handling about where the new node will be put
}
else if (key2 > q->key) {
root = insertright(root,key2);
}
else {
root = insertleft(root,key2);
}
}
}
//cout << "\nroot is : "<< root->key; //not needed ,just for checking
//the value of root
InOrder(root);
cout << endl;
cin >> size;
return 0;
}