PROGRAM FOR BINARY SEARCHING IN TREES using RECURSION.
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
class B_Tree;
class Node
{
private:
int Info;
Node *Left, *Right;
friend class B_Tree;
};
class B_Tree
{
private:
Node *Root;
public:
B_Tree()
{
Root = NULL;
}
Node* Make_Root(int Value)
{
Node *Temp = new Node;
Temp->Info = Value;
Temp->Left = NULL;
Temp->Right = NULL;
return Temp;
}
void Make_Tree()
{
int No;
Node *P, *Q;
cout << "Enter Number To Make Root: ";
cin >> No;
cout << endl;
Root = Make_Root(No);
while(No != 25)
{
cout << "Enter Any Number: ";
cin >> No;
P = Q = Root;
while(P->Info != No && Q != NULL)
{
P = Q;
if(No < P->Info)
Q = P->Left;
else
Q = P->Right;
}
if(P->Info == No)
{
cout << "\nDuplicate Numbers Occurred...!!!\n" << endl;
exit(1);
}
else if(No < P->Info)
Set_Left(P, No);
else
Set_Right(P, No);
}
}
void Set_Left(Node *P, int Value)
{
if(P == NULL || P->Left != NULL)
{
cout << "\nCannot Insert On Left Of It...!!!\n" << endl;
exit(1);
}
P->Left = Make_Root(Value);
}
void Set_Right(Node *P, int Value)
{
if(P == NULL || P->Right != NULL)
{
cout << "\nCannot Insert On Right OF It...!!!\n" << endl;
exit(1);
}
P->Right = Make_Root(Value);
}
int BTree_Search(Node *P, int Value)
{
if(P == NULL)
return 0;
else if(P->Info == Value)
return Value;
else if(Value > P->Info)
BTree_Search(P->Right,Value);
else
BTree_Search(P->Left, Value);
}
void Searching()
{
int No;
cout << "\nEnter Any Value to Search: " ;
cin >> No;
if(BTree_Search(Root, No) == 0)
cout << "\nValue Not Found...!!!\n" << endl;
else
cout << "\nValue Found...!!!\n" << endl;
}
};
int main()
{
cout << "\t\t\tEnter 25 To End......" << endl;
B_Tree Obj;
Obj.Make_Tree();
Obj.Searching();
getch();
return 0;
}