I don't know exactly what means searching using binary tree when I have unsorted array,
maybe I have to create binary search tree first and then search for desired element, something like this:
Code:
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node* left;
struct Node* right;
}node;
node* create_tree(int[],int);
void insert(node**,int);
int *binary_tree_search(node*,int);
void Show(node*);
int main()
{
int array[]={6,7,3,1,2,5,8,9,4,10};
int *x=binary_tree_search(create_tree(array,10),1);
Show(create_tree(array,10));
if(!x)
cout<<"Element not found!";
else
cout<<"element is "<<*x;
}
node* create_tree(int arr[],int len)
{
node* head=new node();
head=0;
for(int i=0;i<len;i++)
insert(&head,arr[i]);
return head;
}
void insert(node**head,int data)
{
if(!*head)
{
*head=new node;
(*head)->data=data;
(*head)->left=0;
(*head)->right=0;
return;
}
if((*head)->data>data)
insert(&(*head)->left,data);
else
insert(&(*head)->right,data);
}
int *binary_tree_search(node* head,int dat)
{
if(!head)
return 0;
if(head->data==dat)
return &(head->data);
else
{
if(head->data>dat)
return binary_tree_search(head->left,dat);
else
return binary_tree_search(head->right,dat);
}
return 0;
}
void Show(node* root)
{
if(root)
{
Show(root->left);
printf("%d ",root->data);
Show(root->right);
}
}
This seems to be unefficient because of allocating memory and creating tree.
Maybe search array with binary tree is not about creating tree at all,but
rearanging array to look like binary tree (!?!)
Please help, I don't know what to do else.