ノードの構造は以下のとおりです。ネイリーツリーを削除するには?各ノードにも親ポインタがあります
struct node
{
int data;
int noofchilds;
node *child[n];
node *parent;
};
再帰的アプローチと非再帰的アプローチの両方に感謝します。
ノードの構造は以下のとおりです。ネイリーツリーを削除するには?各ノードにも親ポインタがあります
struct node
{
int data;
int noofchilds;
node *child[n];
node *parent;
};
再帰的アプローチと非再帰的アプローチの両方に感謝します。
非再帰バージョン:
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;
}
ノードを削除し、子ノードを再帰的に削除します。
完全なツリーを削除する必要がある場合は、親ポインタは問題ではありません(ノード自体が削除されると削除されます)。
反復アルゴリズム:
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.
現在のノードがrootの場合、停止することはできません。あなたにする – Peter
ノード=ルート; do { if(node-> noofchild){ node = node-> child [noofchild-1]; else { node-> parent-> noofchild - ; curr = node-> parent; 空き(ノード); node = curr; } } while(node-> parent ||(node == root && node)) – Peter
あなたは正しいです。私のアルゴリズムは速い草案です... あなたのアルゴリズムは、木が空の場合など、いくつかの問題があるようです。 私は使用します ノード=ルート; while(node){if(node-> noofchild){node-> noofchild--; node = node-> child [node-> noofchild]; } else {curr = node-> parent;フリー(ノード)。ノード= curr; }} – jofel
はいしかし、私は、スタックやキューを使用せずに繰り返しすなわち、それをしたい場合は、何がアプローチすることができ、私は親ポインタがその時間に私たちに利益をもたらすかもしれないと思う – Peter
通常、あなたは主に直接アクセス権を持っている唯一のノードであるので、ルートから始めます...そしてその場合、親はあなたが「下に行く」必要があるので、 ...反復的な解決策がこれに役立つかどうか疑問に思っています。 –
ノード=ルート; do { if(node-> noofchild){ node = node-> child [noofchild-1]; else { node-> parent-> noofchild - ; curr = node-> parent; 空き(ノード); node = curr; } while(node-> parent ||(node == root && node)) – Peter