Write a program to implement binary search on 5 elements.
#include <iostream>
using namespace std;
class SearchTree
{
int item;
SearchTree *leftNode;
SearchTree *rightNode;
public:
SearchTree();
SearchTree(int);
SearchTree* Insert(SearchTree*, int);
void Inorder(SearchTree*);
};
SearchTree ::SearchTree()
: item(0)
, leftNode(NULL)
, rightNode(NULL)
{
}
SearchTree ::SearchTree(int value)
{
item = value;
leftNode = rightNode = NULL;
}
SearchTree* SearchTree ::Insert(SearchTree* node, int value)
{
if (!node)
{
return new SearchTree(value);
}
if (value > node->item)
{
node->rightNode = Insert(node->rightNode, value);
}
else
{
node->leftNode = Insert(node->leftNode, value);
}
return node;
}
void SearchTree ::Inorder(SearchTree* node)
{
if (!node) {
return;
}
Inorder(node->leftNode);
cout << node->item << " ";
Inorder(node->rightNode);
}
int main()
{
SearchTree binary, *node = NULL;
node = binary.Insert(node, 5);
binary.Insert(node, 3);
binary.Insert(node, 2);
binary.Insert(node, 4);
binary.Insert(node, 7);
binary.Insert(node, 6);
binary.Insert(node, 8);
binary.Inorder(node);
return 0;
}
Comments
Leave a comment