1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
|
#include <iostream>
#include <string>
class Node {
public:
Node() : right(nullptr), left(nullptr) { }
Node(std::string n, std::string p) :
name(n), phone(p), right(nullptr), left(nullptr) { }
~Node()
{
std::cout << "Deleting: " << name << ", " << phone << '\n';
delete left;
delete right;
}
friend class Tree;
private:
std::string name;
std::string phone;
Node * right;
Node * left;
};
class Tree {
public:
Tree() : root(nullptr) { }
~Tree()
{
delete root;
}
int insert(std::string n, std::string p);
std::string find(std::string n) const
{
return find(root, n);
}
private:
Node * root;
void insert(Node*& r, std::string n, std::string p);
std::string find(Node*r, std::string n) const;
};
int Tree::insert(std::string n, std::string p)
{
insert(root, n, p);
// Return something once figured out it works correctly
return 0;
}
void Tree::insert(Node*& r, std::string n, std::string p)
{
if (r == nullptr)
{
r = new Node(n,p);
}
else if(n > r->name)
{
insert(r->right, n, p);
}
else
{
insert(r->left, n, p);
}
}
std::string Tree::find(Node*r, std::string n) const
{
if (root == nullptr)
{
std::cout << "No Tree" << std::endl;
return " ";
}
if (r == nullptr)
{
return " ";
}
else if (r->name == n)
{
return r->phone;
}
else if (r->name < n)
{
return find(r->right, n);
}
else
{
return find(r->left, n);
}
}
int main()
{
Tree tree;
tree.insert("fred", "123");
std::string result = tree.find("fred");
std::cout << "1 result = " << result << '\n';
tree.insert("joe", "456");
result = tree.find("fred");
std::cout << "2 result = " << result << '\n';
result = tree.find("joe");
std::cout << "3 result = " << result << '\n';
tree.insert("Suzy Smythe", "789");
tree.insert("Daphne Bentwater", "5356");
tree.insert("Mildred Murfin", "47634");
tree.insert("Richard Lamb", "65676");
result = tree.find("Daphne Bentwater");
std::cout << "4 result = " << result << '\n';
std::cout << "Done\n";
}
|