Binary Search Tree(Searching an element).
SOLVED :::
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* left;
Node* right;
};
Node* root;
Node* NewNode(int data)
{
Node* NewNode = new Node();
NewNode->data = data;
NewNode->left = NULL;
NewNode->right = NULL;
return NewNode;
}
void Traversal(Node* root)
{
if (root == NULL)
{
return;
}
cout << root->data << " ";
Traversal(root->left);
Traversal(root->right);
}
Node* InsertItem(Node* root, int data)
{
if (root == NULL)
{
root = NewNode(data);
}
else if (data <= root->data)
{
root->left = InsertItem(root->left, data);
}
else
{
root->right = InsertItem(root->right, data);
}
return root;
}
bool SearchElement(Node* root, int data)
{
if (root == NULL)
{
cout << " empty" << endl;
return false;
}
else if (root->data == data)
{
return true;
}
else if (data <= root->data)
{
return SearchElement(root->left, data);
}
else
{
return SearchElement(root->right, data);
}
}
int main()
{
root = NULL;
root = InsertItem(root, 8);
root = InsertItem(root, 3);
root = InsertItem(root, 10);
root = InsertItem(root, 1);
root = InsertItem(root, 6);
root = InsertItem(root, 4);
root = InsertItem(root, 7);
root = InsertItem(root, 14);
root = InsertItem(root, 13);
cout << " Enter a item which you want to find: ";
int n;
cin >> n;
cout << endl;
if (SearchElement(root,n) == true)
{
cout << "Your element is found" << endl;
}
else
{
cout << "Element is not found" << endl;
}
Traversal(root);
}
No comments