#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
node *tree=NULL;
node *insert(node *tree,int ele);
void preorder(node *tree);
void inorder(node *tree);
void postorder(node *tree);
int count=1;
void main()
{
int ch,ele;
do
{
cout<<"\n\t----1INSERT A NODE IN A BINARY TREE.";
cout<<"\n\t----2PRE-ORDER TRAVERSAL.";
cout<<"\n\t----3IN-ORDER TRAVERSAL";
cout<<"\n\t----4POST-ORDER TRAVERSAL.";
cout<<"\n\t----5EXIT.";
cout<<"\n\tENTER CHOICE::";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n\tENTER THE ELEMENT::";
cin>>ele;
tree=insert(tree,ele);
break;
case 2:
cout<<"\n\t\****PRE-ORDER TRAVERSAL OF A TREE****";
preorder(tree);
break;
case 3:
cout<<"\n\t****IN-ORDER TRAVERSAL OF A TREE****";
inorder(tree);
break;
case 4:
cout<<"\n\t****POST-ORDER TRAVERSAL OF A TREE****";
postorder(tree);
break;
case 5:
exit(0);
}
}while(ch!=5);
}
node *insert(node *tree,int ele)
{
if(tree==NULL)
{
tree=new node;
tree->left=tree->right=NULL;
tree->data=ele;
count++;
}
else
if(count%2==0)
tree->left=insert(tree->left,ele);
else
tree->right=insert(tree->right,ele);
return(tree);
}
void preorder(node *tree)
{
if(tree!=NULL)
{
cout<<tree->data;
preorder(tree->left);
preorder(tree->right);
getch();
}
}
void inorder(node *tree)
{
if(tree!=NULL)
{
inorder(tree->left);
cout<<tree->data;
inorder(tree->right);
getch();
}
}
void postorder(node *tree)
{
if(tree!=NULL)
{
postorder(tree->left);
postorder(tree->right);
cout<<tree->data;
getch();
}
}
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Here's how a typical binary search tree insertion might be performed in C++:
void insert(int value) { if(root == NULL) root = new Node(value); else insertHelper(root, value); } void insertHelper(Node* node, int value) { if(value < node->key) { if(node->leftChild == NULL) node->leftChild = new Node(value); else insertHelper(node->leftChild, value); } else { if(node->rightChild == NULL) node->rightChild = new Node(value); else insertHelper(node->rightChild, value); } }
public void InsertNode(Node n, double key) { if (n == null) n = new Node(key); else if (key < n.key) { if (n.left == null) { n.left = new Node(key); } else { InsertNode(n.left, key); } } else if (key > n.key) { if (n.right == null) { n.right = new Node(key); } else { InsertNode(n.right, key); } } }
No comments:
Post a Comment