I'm writing a simple program which make Binary Search Tree from some int array and then search for specified value.
Code is:
Code:
#include <iostream>
using namespace std;
class BinaryTree
{
typedef struct NODE
{
int data;
struct NODE* left;
struct NODE* right;
}node;
node *head;
node* InsertPrivate(node*,int);
node* FindPrivate(node*,int);
void Delete(node*);
public:
BinaryTree();
~BinaryTree();
void Insert(int);
node* Find(int);
};
BinaryTree::BinaryTree():head(0){}
BinaryTree::~BinaryTree(){Delete(head);}
void BinaryTree::Insert(int data)
{
head=InsertPrivate(head,data);
}
BinaryTree::node* BinaryTree::InsertPrivate(node* root,int data)
{
if(!root)
{
root=new node;
root->data=data;
root->left=0;
root->right=0;
return root;
}
if(data<=root->data)
root->left=InsertPrivate(root->left,data);
else
root->right=InsertPrivate(root->right,data);
return root;
}
BinaryTree::node* BinaryTree::FindPrivate(node*root,int data)
{
if(!root)
{
return root;
}
if(root->data==data)
return root;
else
{
if(data<root->data)
root=FindPrivate(root->left,data);
else
root=FindPrivate(root->right,data);
}
return root;
}
BinaryTree::node* BinaryTree::Find(int data)
{
node *cur=FindPrivate(head,data);
if(!cur)
cout<<"No element"<<endl;
else
cout<<"Success!"<<endl;
return cur;
}
void BinaryTree::Delete(node *current)
{
if(current !=0)
{
Delete(current->left);
Delete(current->right);
delete current;
}
}
int main()
{
int array[]={5,1,8,2,0,4,7,1,9,2};
BinaryTree b;
for(int i=0;i<10;i++)
b.Insert(array[i]);
b.Find(19);
}
and it seems to work fine. However, I had difficulties to make it work properly. I was getting strange errors when trying to write
node* BinaryTree::FindPrivate(node*root,int data)
and not
BinaryTree::node* BinaryTree::FindPrivate(node*root,int data)
I assume that is because of node is declared within class.
If you can examine this code and give some advices how to make it simpler?
Because of recursion in class I had to write two versions of functions Find and Insert
maybe there is a better way.
Thanks for your help