#include <iostream>
class BST{
private:
class node{
public:
char data;
node *left;
node *right;
node(char ch) : data(ch), left(nullptr), right(nullptr) {}
};
node *root;//pointer to the root
static void visit_inorder(const node*, void(*)(char)) ;
static void insert(node*&n, char data);
public:
BST() : root(nullptr) {}
void insert(char data);
// call a function for each element.
void visit_inorder(void(*f)(char)) const { visit_inorder(root, f); }
};
void BST::insert(BST::node*& n, char data)
{
if (data < n->data)
{
if (n->left)
insert(n->left, data);
else
n->left = new node(data);
}
else if (data > n->data)
{
if (n->right)
insert(n->right, data);
else
n->right = new node(data);
}
}
void BST::insert(char data)
{
if (root == nullptr)
root = new node(data);
else
insert(root, data);
}
void BST::visit_inorder(const BST::node* n, void(*func)(char))
{
if (!n)
return;
visit_inorder(n->left, func);
func(n->data);
visit_inorder(n->right, func);
}
void print_element(char element)
{
std::cout << element << '\n';
}
int main()
{
BST bst;
bst.insert('P');
bst.insert('B');
bst.insert('Z');
bst.insert('R');
bst.insert('C');
bst.visit_inorder(print_element);
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKY2xhc3MgQlNUewpwcml2YXRlOgogICAgY2xhc3Mgbm9kZXsKICAgIHB1YmxpYzoKICAgICAgICBjaGFyIGRhdGE7CiAgICAgICAgbm9kZSAqbGVmdDsKICAgICAgICBub2RlICpyaWdodDsKCiAgICAgICAgbm9kZShjaGFyIGNoKSA6IGRhdGEoY2gpLCBsZWZ0KG51bGxwdHIpLCByaWdodChudWxscHRyKSB7fQogICAgfTsKICAgIG5vZGUgKnJvb3Q7Ly9wb2ludGVyIHRvIHRoZSByb290CgogICAgc3RhdGljIHZvaWQgdmlzaXRfaW5vcmRlcihjb25zdCBub2RlKiwgdm9pZCgqKShjaGFyKSkgOwogICAgc3RhdGljIHZvaWQgaW5zZXJ0KG5vZGUqJm4sIGNoYXIgZGF0YSk7CgpwdWJsaWM6CiAgICBCU1QoKSA6IHJvb3QobnVsbHB0cikge30KCiAgICB2b2lkIGluc2VydChjaGFyIGRhdGEpOwoKICAgIC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