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
|
#include <iostream>
#include <string>
#include <initializer_list>
struct Node {
char data {};
Node* left {};
Node* right {};
Node* mid {};
Node(char c) : data(c) {}
};
class BSTree
{
Node* root {};
void insert(char, Node*&);
void traverse(const Node*) const;
std::string get_nodes(int, const Node*) const;
void remove(const Node*);
public:
BSTree() {}
~BSTree() { remove(root); }
BSTree(const std::string&);
BSTree(const std::initializer_list<char>& chars);
void insert(char letter) { insert(letter, root); }
void traverse() const { traverse(root); }
std::string get_nodes(int n) const { return get_nodes(n, root); }
};
BSTree::BSTree(const std::initializer_list<char>& chars)
{
for (const auto c : chars)
insert(c);
}
BSTree::BSTree(const std::string& S)
{
for (const auto c : S)
insert(c);
}
void BSTree::remove(const Node* leaf)
{
if (leaf) {
remove(leaf->left);
remove(leaf->mid);
remove(leaf->right);
delete leaf;
}
}
void BSTree::insert(char letter, Node*& leaf)
{
if (!leaf)
leaf = new Node(letter);
else if (letter < leaf->data)
insert(letter, leaf->left);
else if (letter > leaf->data)
insert(letter, leaf->right);
else
insert(letter, leaf->mid);
}
void BSTree::traverse(const Node* leaf) const
{
if (leaf) {
traverse(leaf->left);
traverse(leaf->mid);
std::cout << leaf->data;
traverse(leaf->right);
}
}
std::string BSTree::get_nodes(int n, const Node* leaf) const
{
std::string result;
if (leaf) {
result = get_nodes(n, leaf->left) + get_nodes(n, leaf->mid);
if ((leaf->left != nullptr) + (leaf->mid != nullptr) + (leaf->right != nullptr) == n)
result += leaf->data;
result += get_nodes(n, leaf->right);
}
return result;
}
int main()
{
//BSTree T("eafhbgbahie");
BSTree T {'e','a','f','h','b','g','b','a','h','i','e'};
T.traverse();
std::cout << '\n';
for (int n = 0; n <= 3; ++n)
std::cout << n << ": " << T.get_nodes(n) << '\n';
}
|