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
|
#include <iostream>
#include <string>
class bst
{
struct node
{
node* left_ = nullptr;
node* right_ = nullptr;
explicit node(std::string const& data, node* left = nullptr, node* right = nullptr)
: left_(left), right_(right), data_(data)
{}
std::string data_;
bool insert(std::string const& data)
{
return (data < data_)? insert_subtree(data, left_)
: (data_ < data )? insert_subtree(data, right_)
: false;
}
} *root_ = nullptr;
friend bool insert_subtree(std::string const& data, node*& child)
{
return child? child->insert(data): bool{child = new node(data)};
}
void destroy(node* n)
{
if (n)
{
destroy(n->left_);
destroy(n->right_);
}
delete n;
}
void print_in_order_impl(node* const n) const
{
if (n)
{
print_in_order_impl(n->left_);
std::cout << n->data_;
print_in_order_impl(n->right_);
}
}
public:
bool insert(std::string const& data)
{
return insert_subtree(data, root_);
}
void print_in_order() const
{
print_in_order_impl(root_);
}
bst() = default;
bst(bst const&) = delete;
bst& operator=(bst) = delete;
~bst() { destroy(root_); }
};
int main()
{
bst tree;
for (auto elt : { "D", "G", "A", "H", "F", "J", "E", "C", "I", "B" })
tree.insert(elt);
tree.print_in_order();
}
|