Friday, May 1, 2015

Insert A Value on Left Side which is greater Then Root and Small Value on Right side ~ C++ Tree codes

Insert A Value on Left Side which is greater Then Root and Small Value on Right side

#include<iostream.h>
#include<conio.h>
class Node{
private:
int data;
Node* right,*q,*p;
Node* left;
public:
Node(){
root=NULL;
right=left=NULL;
}Node *root;


void insert(int data){
Node* newnode = new Node();
newnode->data = data;
if (root == NULL){
root=newnode;
return;
}
Node *p,*q;
p=q=root;
while (q!=NULL){
p=q;
if (newnode->data< q->data)
q = q->right;
else q = q->left;
}
if (newnode->data< p->data)
p->right = newnode;
else p->left = newnode;
}




void inorder(Node *root){
if (root == NULL) return;
else {
inorder(root->left);
cout << root->data <<"  ";
inorder(root->right);
}
}

void preorder(Node *root){
if (root == NULL) return;
else {
cout << root->data <<"  ";
preorder(root->left);
preorder(root->right);
}
}

void postorder(Node *root){
if (root == NULL) return;
else {
postorder(root->left);
postorder(root->right);
cout << root->data <<"  ";
}
}



};

void main()
{
int c,A[]={9,4,3,2,5,6,8,1,33,12,44};
Node b;
clrscr();
for(int i=0;i<=10;i++){
b.insert(A[i]); }
cout<<"\n\nGreater then root on left side and smaller values on Right side\n\n";
cout<<"\n\nInorder triversal: ";
b.inorder(b.root);
cout<<"\n\nPreorder triversal: ";
b.preorder(b.root);
cout<<"\n\nPostorder triversal: ";
b.postorder(b.root);
cout<<"\n\n----------+--------------+---------------------+-------------\n\n";

getch();

}





Share this

0 Comment to "Insert A Value on Left Side which is greater Then Root and Small Value on Right side ~ C++ Tree codes"