struct Node;
using NodePtr = std::unique_ptr<Node>;
struct Node
{
int value;
Node* parent = nullptr;
NodePtr left = nullptr;
NodePtr right = nullptr;
Node(int value_): value(value_){}
};
void insert(NodePtr& root, NodePtr&& new_node)
{
auto const value = new_node->value;
auto new_node_ref = &root;
while ((*new_node_ref) != nullptr){
if ((*new_node_ref)->value < value){
new_node_ref = &((*new_node_ref)->right);
}else{
new_node_ref = &((*new_node_ref)->left);
}
}
(*new_node_ref) = std::move(new_node);
}
NodePtr create(const std::vector<int>& data)
{
if (data.empty ()){
return NodePtr();
}
auto root = std::make_unique<Node>(data.front ());
std::for_each(data.begin () + 1, data.cend (),
[&](int value){ insert (root, std::make_unique<Node>(value));});
return std::move(root);
}
void traverse(const NodePtr& root)
{
if (root != nullptr){
traverse (root->left);
std::printf("%d ", root->value);
traverse (root->right);
}
}
NodePtr overturn(NodePtr& root)
{
if (root != nullptr){
overturn (root->left);
overturn (root->right);
std::swap(root->left, root->right);
}
return std::move(root);
}