The problem is that I cannot return a false value in the binary tree.
#include <iostream>
#include <string>
using namespace std;
struct Node
{
int Identification;
string full_name;
Node *left;
Node *right;
};
Node *newNode(int id, string name)
{
Node *temp = new Node;
temp->Identification = id;
temp->full_name = name;
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* insert(Node* node, int id, string name)
{
if ( node == NULL)
{
return newNode(id,name);
}
if(id < node->Identification)
{
node->left = insert(node->left, id, name);
}
else if (id > node->Identification)
{
node->right = insert(node->right, id, name);
}
return node;
}
bool search(Node* root, int id)
{
if (root == NULL || root->Identification == id)
{
cout << root->full_name << endl;
return true;
}
else if (root != NULL && root->Identification != id)
{
cout << "Record not found";
return false;
}
if (root->Identification < id)
{
return search(root->right, id);
}
return search(root->left, id);
}
int main()
{
int searching;
Node *root = NULL;
root = insert(root, 1021, "John Williams");
root = insert(root, 1057, "Bill Witherspoon");
root = insert(root, 2487, "Jennifer Twain");
root = insert(root, 3769, "Sophia Lancaster");
root = insert(root, 1017, "Debbie Reece");
root = insert(root, 1275, "George McMullen");
root = insert(root, 1899, "Ashley Smith");
root = insert(root, 4218, "Josh Plemmons");
cout << "Enter ID to find employe name ";
cin >> searching;
search(root, searching);
return 0;
}
It works when I types like 444
and returns false
, No Id found
. And when I type 1021
, it return true
, John Williams
. But when I use other IDs like for example 1899
, which correspond with Ashley smith
, it returns false
. So I do not know what is the problem.