In: Computer Science
Implement a function to find a node in a binary search tree. Using the following class and function definition. If a node with a matching value is found, return a pointer to it. If no match is found, return nullptr.
#include <iostream>
class BTNode {
public:
int item;
BTNode *left;
BTNode *right;
BTNode(int i, BTNode *l=nullptr, BTNode
*r=nullptr):item(i),left(l),right(r){}
};
BTNode *root = nullptr;
BTNode *find(int item)
{
//implement code here
return nullptr;
}
int main()
{
root = new BTNode(10, new BTNode(1), new BTNode(20));
BTNode *t1 = find(10);
if (t1)
std::cout << "Found " << t1->item <<
std::endl;
else
std::cout << "Should have found 10." <<
std::endl;
BTNode *t2 = find(1);
if (t1)
std::cout << "Found " << t2->item <<
std::endl;
else
std::cout << "Should have found 1." << std::endl;
BTNode *t3 = find(20);
if (t3)
std::cout << "Found " << t3->item <<
std::endl;
else
std::cout << "Should have found 20." <<
std::endl;
BTNode *t4 = find(100);
if (t4)
std::cout << "Should have found 20." << std::endl;
else
std::cout << "Did not find 100." << std::endl;
return 0;
}
PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU
NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR
YOU
#include <iostream>
class BTNode
{
public:
int item;
BTNode *left;
BTNode *right;
BTNode(int i, BTNode *l = nullptr, BTNode *r = nullptr) : item(i), left(l), right(r) {}
};
BTNode *root = nullptr;
BTNode *find(int item)
{
BTNode *temp = root;
while (temp != NULL)
{
if (item > temp->item)
temp = temp->right;
else if (item < temp->item)
temp = temp->left;
else
{
return temp;
}
}
return nullptr;
}
int main()
{
root = new BTNode(10, new BTNode(1), new BTNode(20));
BTNode *t1 = find(10);
if (t1)
std::cout << "Found " << t1->item << std::endl;
else
std::cout << "Should have found 10." << std::endl;
BTNode *t2 = find(1);
if (t1)
std::cout << "Found " << t2->item << std::endl;
else
std::cout << "Should have found 1." << std::endl;
BTNode *t3 = find(20);
if (t3)
std::cout << "Found " << t3->item << std::endl;
else
std::cout << "Should have found 20." << std::endl;
BTNode *t4 = find(100);
if (t4)
std::cout << "Should have found 20." << std::endl;
else
std::cout << "Did not find 100." << std::endl;
return 0;
}