After getting through of some video lessons about such Binary Tree, Binary Search Tree, I get comprehend of this kind of algorithm method and would like to do a brief implementation. Following is my Cpp code for creating, inserting, and searching of Binary Search Tree:
Test platform: whatever, it's compatibility free, but I was on Visual Studio 2017 with Windows 10.
#include <windows.h>
#include <vector>
#include <iostream>
using namespace std;
struct BSTnode {
int data;
BSTnode * left;
BSTnode * right;
};
BSTnode * GetBSTnode(int data)
{
BSTnode * newNode = new BSTnode();
newNode->data = data;
newNode->left = newNode->right = NULL;
cout << "created a node for data is " << data << endl;
return newNode;
}
void InsertNode(BSTnode **rootPtr, int data) {
if (*rootPtr == NULL)
{
cout << "no any data in current root, inserting here" << endl;
*rootPtr = GetBSTnode(data);
}
else if(data <= ((*rootPtr)->data))
{
cout << "at position "<< (*rootPtr)->data <<" data is smaller than current root, searching for insert leftward" << endl;
InsertNode(((&(*rootPtr)->left)), data);
}
else
{
cout << "at position " << (*rootPtr)->data << " data is greater than current root, searching for insert rightward" << endl;
InsertNode(((&(*rootPtr)->right)), data);
}
}
void SearchNode(BSTnode * root, int data) {
if (root == NULL)
{
cout << " can't find any data" << endl;
return;
}
else if ((root->data == data))
{
cout << "found data" << endl;
return;
}
else if (data <= root->data)
{
cout << "at position " << root->data << ", data you typed is smaller or equal to current root, searching leftward" << endl;
return SearchNode(root->left, data);
}
else
{
cout << "at position " << root->data << ", data you typed is greater or equal to current root, searching leftward" << endl;
return SearchNode(root->right, data);
}
}
int main(int argc, char*argv[])
{
BSTnode * root = NULL;
vector<int> numbers;
numbers.push_back(15); numbers.push_back(19); numbers.push_back(11); numbers.push_back(17); numbers.push_back(14);
for (auto &it : numbers)
{
cout << "now inserting number " << it << endl;
InsertNode(&root, it);
cout << endl;
}
for(;;)
{
int number;
cout << endl;
cout << "Enter number be searched\n";
cin >> number;
SearchNode(root, number);
cout << endl;
}
Sleep(5000);
return 0;
}
comment:
I think the information in cout function is clear enuf.