I made binary search tree using classes. I would like to know if I could do something better or maybe there is something wrong with my code. I decided not to use recursion. I would be very thankful for any suggestions.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Bst
{
private:
struct BstNode
{
int data;
BstNode* left;
BstNode* right;
};
public:
Bst()
{
root = nullptr;
}
BstNode* insert(int data)
{
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
bool add(int number)
{
if (root == nullptr)
{
root = insert(number);
}
else
{
BstNode* tmp_root = root;
while (tmp_root != nullptr)
{
if (number <= tmp_root->data)
{
if (tmp_root->left == nullptr)
{
tmp_root->left = insert(number);
return true;
}
else
{
tmp_root = tmp_root->left;
}
}
else
{
if (tmp_root->right == nullptr)
{
tmp_root->right = insert(number);
return true;
}
else
{
tmp_root = tmp_root->right;
}
}
}
}
return false;
}
bool search(int number)
{
BstNode* tmp_root = root;
while (tmp_root != nullptr)
{
if (number == tmp_root->data) return true;
if (number < tmp_root->data)
{
tmp_root = tmp_root->left;
continue;
}
if (number > tmp_root->data)
{
tmp_root = tmp_root->right;
}
}
return false;
}
private:
BstNode* root;
};
int main()
{
Bst tree;
tree.add(10);
tree.add(15);
tree.add(2);
tree.add(4);
tree.add(7);
for (int i = 1; i <= 20; i++)
{
string exist = tree.search(i) ? "YES" : "NO";
cout << i << ": " << exist << endl;
}
system("pause");
return 0;
}