#include #include #include #include template struct Node{ T value; std::unique_ptr> small; std::unique_ptr> big; void dump(std::ofstream& ofs) const; }; template class Tree{ std::unique_ptr> root; public: bool insert(T val); void del(T val); void print() const; }; template void del(T val); template bool Tree::insert(T val){ std::unique_ptr> node = std::make_unique>(); node->value = val; if (!root){ root.swap(node); return true; } else{ Node* temp = root.get(); while(temp){ if(val < temp->value){ if(temp->small) temp = temp->small.get(); else{ temp->small.swap(node); return true; } } else if(val > temp->value){ if(temp->big) temp = temp->big.get(); else{ temp->big.swap(node); return true; } } else return false; } return false; } } template void Node::dump(std::ofstream& ofs) const { if (small) { ofs << value << " -> " << small->value << '\n'; small->dump(ofs); } if (big) { ofs << value << " -> " << big->value << '\n'; big->dump(ofs); } } template void Tree::print() const { std::ofstream ofs; ofs.open("viz.dot"); ofs << "digraph Tree {\n"; if(root) root->dump(ofs); ofs << "}"; ofs.close(); system("cat viz.dot | dot -Tx11"); } int main(){ Tree t; std::vector v = {3, 6, 8, 0, -1, 1, 4, 2}; for(auto i : v){ if(t.insert(i)) std::cout << "added " << i << "\n"; else std::cout << "failed at " << i << "\n"; t.print(); } }