The structure of the node is below.
struct node
{
int data;
int noofchilds;
node *child[n];
node *parent;
};
I would appreciate both recursive and non-recursive approaches.
The structure of the node is below.
struct node
{
int data;
int noofchilds;
node *child[n];
node *parent;
};
I would appreciate both recursive and non-recursive approaches.
Non-recursive version:
struct node {
struct node *parent;
unsigned nchild;
struct node *child[XXX];
int data;
};
void deltree(struct node *np)
{
struct node *par;
while (np) {
/* if this node has any children, start by
** "descending" to the highest numbered child and kill that first.
*/
if (np->nchild--) {
np = np->child[np->nchild];
continue;
}
/* when we arrive here, *np has no more children left,
** so kill it, and step up to its parent
*/
par = node->parent;
// if np->child was obtained via malloc() uncomment next line
// free (np->child);
free (np);
np = par;
}
return;
}
Remove the node and recursively remove its children.
If you have to remove the complete tree (as your question seems to be), the parent pointer does not matter (and is removed with the removal of the node itself).
An iterative algorithm:
Start at the parent node.
Then do the following actions as long as possible:
if the current node has one or more children:
set one of the children nodes as the (next) current node
else
delete the current node and use its parent as the (next) current node.
if the current node was the root node (which has no parent), stop.