Skip to content

Instantly share code, notes, and snippets.

@sjswitzer
Created December 15, 2017 23:21
Show Gist options
  • Save sjswitzer/7b3b510649a83708fe827db9f1eeec2b to your computer and use it in GitHub Desktop.
Save sjswitzer/7b3b510649a83708fe827db9f1eeec2b to your computer and use it in GitHub Desktop.
//
// main.cpp
// TreeShared
//
// Created by stan on 12/8/17.
// Copyright © 2017 stan. All rights reserved.
//
#include <iostream>
template <class T> class Tree;
template <class T>
class Node
{
public:
Node(const T& v)
: value(v)
{}
~Node() {
for (Node *child = _children, *nxt; child; child = nxt) {
nxt = child->_next;
delete child;
}
}
Node *_parent = nullptr, *_next = nullptr, *_children = nullptr;
Tree<T> *_root;
T value;
std::shared_ptr<Node> insert(const T& v) {
Node *n = new Node(v);
n->_next = _children;
n->_parent = this;
n->_root = _root;
_children = n;
return std::shared_ptr<Node<T>>(root(), n);
}
std::shared_ptr<Tree<T>> root()
{
return _root->shared_from_this();
}
std::shared_ptr<Tree<T>> parent()
{
if (_parent) {
return std::shared_ptr<Node<T>>(root(), _parent);
}
return {};
}
std::shared_ptr<Tree<T>> children()
{
if (_children) {
return std::shared_ptr<Node<T>>(root(), _children);
}
return {};
}
std::shared_ptr<Tree<T>> next()
{
if (_next) {
return std::shared_ptr<Node<T>>(root(), _next);
}
return {};
}
void print(const std::string &prefix = "")
{
std::cout << prefix << value << '\n';
for (Node *child = _children; child; child = child->_next) {
child->print(prefix + " ");
}
}
};
template <class T>
class Tree: public Node<T>, public std::enable_shared_from_this<Tree<T>>
{
public:
Tree(const T& v)
: Node<T>(v)
{
Node<T>::_root = this;
}
~Tree()
{
std::cout << "deleted\n";
}
static std::shared_ptr<Tree<T>> create(const T &v)
{
return std::make_shared<Tree>(v);
}
};
int main(int argc, const char * argv[]) {
auto t = Tree<int>::create(1);
t->insert(2);
auto n = t->insert(3);
t->insert(4);
n->insert(5);
t = nullptr;
n->root()->print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment