#include <iostream>
#include <memory>
#include <utility>
#include <vector>
template <typename T>
class Tree : public std::enable_shared_from_this<Tree<T>>
{
public:
template<typename...Args>
explicit Tree(Args&&...args) : m_data(std::forward<Args>(args)...) {}
std::shared_ptr<Tree> AddChild(const std::shared_ptr<Tree>& child)
{
using base = std::enable_shared_from_this<Tree>;
m_children.push_back(child);
child->m_parent = base::shared_from_this();
return child;
}
template<typename...Args>
std::shared_ptr<Tree> CreateChild(Args&&...args)
{
return AddChild(std::make_shared<Tree>(std::forward<Args>(args)...));
}
private:
T m_data;
std::weak_ptr<Tree> m_parent;
std::vector<std::shared_ptr<Tree>> m_children;
};
int main()
{
const auto root_ptr = std::make_shared<Tree<int>>();
root_ptr->CreateChild(1)->CreateChild(11)->CreateChild(111);
root_ptr->CreateChild(2)->CreateChild(21)->CreateChild(211);
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bWVtb3J5PgojaW5jbHVkZSA8dXRpbGl0eT4KI2luY2x1ZGUgPHZlY3Rvcj4KCnRlbXBsYXRlIDx0eXBlbmFtZSBUPgpjbGFzcyBUcmVlIDogcHVibGljIHN0ZDo6ZW5hYmxlX3NoYXJlZF9mcm9tX3RoaXM8VHJlZTxUPj4KewpwdWJsaWM6CgogIHRlbXBsYXRlPHR5cGVuYW1lLi4uQXJncz4KICBleHBsaWNpdCBUcmVlKEFyZ3MmJi4uLmFyZ3MpIDogbV9kYXRhKHN0ZDo6Zm9yd2FyZDxBcmdzPihhcmdzKS4uLikge30KCiAgc3RkOjpzaGFyZWRfcHRyPFRyZWU+IEFkZENoaWxkKGNvbnN0IHN0ZDo6c2hhcmVkX3B0cjxUcmVlPiYgY2hpbGQpCiAgewogICAgdXNpbmcgYmFzZSA9IHN0ZDo6ZW5hYmxlX3NoYXJlZF9mcm9tX3RoaXM8VHJlZT47CiAgICBtX2NoaWxkcmVuLnB1c2hfYmFjayhjaGlsZCk7CiAgICBjaGlsZC0+bV9wYXJlbnQgPSBiYXNlOjpz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