Skip to content

Instantly share code, notes, and snippets.

@legnaleurc
Last active September 23, 2015 21:28
Show Gist options
  • Save legnaleurc/619053 to your computer and use it in GitHub Desktop.
Save legnaleurc/619053 to your computer and use it in GitHub Desktop.
Binary Node
#include <memory>
#include <iostream>
class Node: public std::enable_shared_from_this< Node > {
public:
typedef std::shared_ptr< Node > NodeSP;
typedef std::weak_ptr< Node > NodeWP;
static NodeSP create( int value ) {
return NodeSP( new Node( value ) );
}
~Node() {
std::cout << this->value << std::endl;
}
void setLeft( NodeSP node ) {
this->left = node;
node->parent = this->shared_from_this();
}
void setRight( NodeSP node ) {
this->right = node;
node->parent = this->shared_from_this();
}
NodeSP getLeft() const {
return this->left;
}
NodeSP getRight() const {
return this->right;
}
private:
explicit Node( int value ): std::enable_shared_from_this< Node >(), parent(), left(), right(), value( value ) {
}
Node( const Node & );
Node & operator =( const Node & );
NodeWP parent;
NodeSP left;
NodeSP right;
int value;
};
int main() {
auto root = Node::create( 0 );
{
auto l = Node::create( 1 );
auto r = Node::create( 2 );
root->setLeft( l );
root->setRight( r );
l = Node::create( 3 );
r = Node::create( 4 );
root->getLeft()->setLeft( l );
root->getLeft()->setRight( r );
l = Node::create( 5 );
r = Node::create( 6 );
root->getRight()->setLeft( l );
root->getRight()->setRight( r );
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment