Skip to content

Instantly share code, notes, and snippets.

@andr1972
Created August 14, 2017 21:43
Show Gist options
  • Save andr1972/a1f5d7a45b08c77414a444462547d8a1 to your computer and use it in GitHub Desktop.
Save andr1972/a1f5d7a45b08c77414a444462547d8a1 to your computer and use it in GitHub Desktop.
Iterative deleting tree
#include <stack>
#include <iostream>
#include <stdint.h>
#include <random>
#include <algorithm>
using namespace std;
const int height = 10000;
uint8_t choos[height];
int active = 0;
const int maxChildren = 3;
struct Node
{
Node(int value) :value(value)
{
active++;
for (int i = 0; i<maxChildren; i++)
children[i] = nullptr;
}
~Node()
{
active--;
}
int value;
Node *children[maxChildren];
};
Node *createLongTree()
{
mt19937 gen(0);
uniform_int_distribution<int16_t> dis(0, maxChildren - 1);
uniform_int_distribution<int16_t> dis2(1, maxChildren - 1);
uniform_int_distribution<int16_t> disoth(0, 5);
Node *node;
Node *child = new Node(0);
Node *head = child;
for (int i = 0; i < height; i++)
{
node = child;
choos[i] = dis(gen);
child = new Node(0);
node->children[choos[i]] = child;
if (dis(gen) == 0)
{
int second = (choos[i] + dis2(gen)) % maxChildren;
node->children[second] = new Node(0);
}
}
return head;
}
void IterTreeDelete(Node *head)
{
Node *node = head;
Node *prevnode;
int index = 0;
stack<pair<Node *, int>> *st = new stack<pair<Node *, int>>();
do
{
Node* tmpnode;
prevnode = node;
int childCount = 0;
int numberOneChild = -1;
for (int i = 0; i < maxChildren; i++)
{
if (node->children[i])
{
childCount++;
numberOneChild = i;
}
}
if (childCount == 1)//optimalization for degenerated trees
{
Node *tmp = node;
node = node->children[numberOneChild];
delete tmp;
continue;
}
index = 0;
while (index < maxChildren && !node->children[index]) index++;
if (index < maxChildren) node = node->children[index];
if (index < maxChildren)
{
st->push(make_pair(prevnode, index));
index = 0;
}
else
{
delete node;
if (st->empty()) return;
pair<Node *, int> p = st->top();
node = p.first; index = p.second;
st->pop();
index++;
while (index < maxChildren && !node->children[index]) index++;
while (index >= maxChildren)
{
delete node;
pair<Node *, int> p = st->top();
node = p.first; index = p.second;
st->pop();
if (st->empty())
{
delete node;
return;
}
index++;
while (index < maxChildren && !node->children[index]) index++;
}
if (index < maxChildren)
{
st->push(make_pair(node, index));
while (index < maxChildren && !node->children[index]) index++;
if (index < maxChildren) node = node->children[index];
}
}
} while (true);
delete st;
}
int main()
{
Node *head = createLongTree();
IterTreeDelete(head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment