Skip to content

Instantly share code, notes, and snippets.

@arthur-tacca
Last active September 14, 2017 08:28
Show Gist options
  • Save arthur-tacca/9c53fa4725b69453062aa226641d04a8 to your computer and use it in GitHub Desktop.
Save arthur-tacca/9c53fa4725b69453062aa226641d04a8 to your computer and use it in GitHub Desktop.
// Like solution 4, but uses a dummy Node object for leaf nodes instead of *this
// The implicitly declared constructor is fine because we don't need to fix up *this
class Node
{
public:
Node(int d, Pool& pool)
: level{d}
, l{d > 0 ? pool.emplace_back(Node(d - 1, pool)) : dummy}
, r{d > 0 ? pool.emplace_back(Node(d - 1, pool)) : dummy}
{
}
int level;
const Node& l;
const Node& r;
int check() const
{
if(!(&l == dummy))
return l.check() + 1 + r.check();
else
return 1;
}
private:
static Node dummy;
Node(): level(0), l(dummy), r(dummy) {}
};
// Need to *define* dummy as well as declare
Node Node::dummy;
// Like solution 4, but uses pointers, and uses nullptr for leaf nodes
// The implicitly declared constructor is fine because we don't need to fix up *this
struct Node {
Node(int d, Pool& pool)
: level{d}
, l{d > 0 ? &pool.emplace_back(Node(d - 1, pool)) : nullptr}
, r{d > 0 ? &pool.emplace_back(Node(d - 1, pool)) : nullptr}
{
}
int level;
const Node* const l;
const Node* const r;
int check() const
{
if(l)
return l->check() + 1 + r->check();
else
return 1;
}
};
// If you're prepared to mix solution 2 with using nullptr instead of this,
// you get the simplest solution of all; the Node code is totally separated
// from the code defining the place we choose to store instances of it.
struct Node {
int level;
const Node* const l;
const Node* const r;
int check() const
{
if(l)
return l->check() + 1 + r->check();
else
return 1;
}
};
using Pool = std::deque<Node>;
Node* make(int d, Pool& pool)
{
Node* l = d > 0 ? make(d - 1, pool) : nullptr;
Node* r = d > 0 ? make(d - 1, pool) : nullptr;
return &pool.emplace_back(d, l, r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment