As the title says, the objective is to free a binary tree without using the stack or allocating memory.
This was required for a kernel module where resources were limited.
Result has a complexity of \$ O \left( n \right) \$.
template<typename T>
struct Node
{
T data;
Node* left;
Node* right;
};
// Utility function to find the bottom left
// Of the tree (because that has a NULL left
// pointer that we can use to store information.
Node* findBottomLeft(Node* t)
{
while(t->left != NULL)
{
t = t->left;
}
return t;
}
void freeTree(Node* t)
{
if (t == NULL)
{ return;
}
// Points at the bottom left node.
// Any right nodes are added to the bottom left as we go down
// this progressively flattens the tree into a list as we go.
Node* bottomLeft = findBottomLeft(t);
while(t != NULL)
{
// Technically we don't need the if (it works fine without)
// But it makes the code easier to reason about with it here.
if (t->right != NULL)
{
bottomLeft->left = t->right;
bottomLeft = findBottomLeft(bottomLeft);
}
// Now just free the curent node
Node* old = t;
t = t->left;
delete old;
}
}
unique_ptr
and the like would be more idiomatic and exception safe, but as you are in a kernel environment, exceptions are not allowed and your recursion requirement rules out the use ofunique_ptr
. (Then again I am wondering why you are programming C++ in the (supposedly Linux-)kernel) \$\endgroup\$