I implemented a BST and so far I have all of my functions working. When I search for an element in the BST it is able to find all elements greater than and equal to 9. Anything less than 9 returns FALSE although the element is in there. I know that the elements are linked correctly because when I print them in post order they appear. Any help?
#include <iostream>
using namespace std;
class Node {
public:
Node(int data){
this->data = data;
this->LeftChild = NULL;
this->RightChild = NULL;
};
int data;
Node* LeftChild;
Node* RightChild;
};
class BST {
private:
Node* root;
public:
BST(){
root = nullptr;
}
Node* getRoot(){ return this->root; };
void printTree(Node *root){
if (root != NULL)
{
printTree(root->LeftChild);
printTree(root->RightChild);
cout << root->data << " ";
}
}
void InsertNode(int data){
Node *current;
Node * trailCurrent = nullptr;
Node *z = new Node(data);
if(root == NULL){
root = new Node(data);
}
else{
current = root;
while(current!= nullptr){
trailCurrent = current;
if(current->data == data){
cout<< "KEY IS ALREADY IN TREE ";
return;
}
else if(current->data > data){
current = current->LeftChild;
}
else{
current = current->RightChild;
}
}
if(trailCurrent->data > data){
trailCurrent->LeftChild = z;
}
else{
trailCurrent->RightChild = z;
}
}
}
int Largest(){
int max;
while(root->RightChild!=NULL){
root = root->RightChild;
}
max = root->data;
return max;
}
bool FindNode(Node * root,int data){
if(root == NULL){
return false;
}
else if( data == root->data){
return true;
}
else if(data < root->data){
return FindNode(root->LeftChild, data);
}
else{
return FindNode(root->RightChild, data);
}
}
};
int main(){
BST myBst;
cout << "INSERTING\n";
myBst.InsertNode(7);
myBst.InsertNode(20);
myBst.InsertNode(8);
myBst.InsertNode(9);
myBst.InsertNode(6);
myBst.InsertNode(1);
myBst.InsertNode(19);
myBst.InsertNode(15);
myBst.InsertNode(2);
myBst.InsertNode(10);
cout << myBst.getRoot()->data;
myBst.printTree(myBst.getRoot());
cout << "THE MAX ELEMENT IN THE TREE IS"<< endl;
cout << myBst.Largest();
cout << "\n\n SEARCHING FOR ELEMENTS" << endl;
cout << myBst.FindNode(myBst.getRoot(), 6);
return 0;
}
** program output ** searching for element 10 returns ** TRUE** searching for element 6 returns ** FALSE**