#include <iostream>
#include <string>
struct Node
{
int id;
std::string data;
Node *left;
Node *right;
Node(int n)
: id(n)
, data(std::to_string(n))
, left(nullptr)
, right(nullptr)
{
std::cout << "Creating Node(" << id << ")\n";
}
~Node()
{
std::cout << "Destroying Node(" << id << ")\n";
}
};
class BST
{
private:
Node *root;
protected:
// provided for recursion.
std::string getEntry(Node const *p, int id) const
{
// nowhere else to go; return empty string
if (p == nullptr)
return "";
// walk down left tree if needed
if (id < p->id)
return getEntry(p->left, id);
// walk down right tree if needed
if (p->id < id)
return getEntry(p->right, id);
// neither left nor right needed; must be this.
return p->data;
}
// provided for recursion
void addNode(Node *& rp, int id)
{
if (rp == nullptr)
{
rp = new Node(id);
return;
}
if (id < rp->id)
addNode(rp->left, id);
else if (rp->id < id) // note: remove if-condition to allow duplicate insertions
addNode(rp->right, id);
}
// provided for recursion
void clear(Node *& rp)
{
if (rp)
{
clear(rp->left);
clear(rp->right);
delete rp;
rp = nullptr;
}
}
public:
BST() : root(nullptr) {}
// delete these for rule of three/five compliance
BST(BST const&) = delete;
BST& operator =(BST const&) = delete;
virtual ~BST()
{
clear(root);
}
// invokes the recursive member with root pointer as starting point.
void addNode(int id)
{
addNode(root, id);
}
// invokes the recursive member with root pointer as starting point.
std::string getEntry(int id) const
{
return getEntry(root, id);
}
};
int main()
{
BST bst;
// add some sample numbers
bst.addNode(42);
bst.addNode(5);
bst.addNode(100);
bst.addNode(16);
// tests:
std::cout << bst.getEntry(1) << '\n'; // blank line
std::cout << bst.getEntry(5) << '\n'; // 5
std::cout << bst.getEntry(6) << '\n'; // blank line
std::cout << bst.getEntry(41) << '\n'; // blank line
std::cout << bst.getEntry(42) << '\n'; // 42
std::cout << bst.getEntry(43) << '\n'; // blank line
std::cout << bst.getEntry(99) << '\n'; // blank line
std::cout << bst.getEntry(100) << '\n'; // 100
std::cout << bst.getEntry(101) << '\n'; // blank line
return 0;
}