2012-02-23 2 views

ответ

1

нерекурсивна версия:

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; 
} 
0

Удалите узел и рекурсивно удалите его дочерние элементы.

Если вам нужно удалить полное дерево (как кажется ваш вопрос), родительский указатель не имеет значения (и удаляется с удалением самого узла).

+0

да, но если я хочу сделать это итеративно т.е. без использования стека или очереди, то, что может быть подход, Я думаю, что родительский указатель может принести нам пользу в то время – Peter

+0

Обычно вы начинаете с корня, так как это единственный узел, в котором вы, как правило, также имеете прямой доступ ... и в этом случае родитель не нужен, поскольку вам нужно только «спуститься» вниз, ... Мне интересно, поможет ли итеративное решение. –

+0

node = root; do { if (node-> noofchild) { node = node-> child [noofchild-1]; прочее { node-> parent-> noofchild -; curr = node-> parent; свободный (узел); node = curr; } } while (node-> parent || (node ​​== root && node)) – Peter

0

итерационный алгоритм:

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. 
+0

мы не можем остановить, если текущий узел является корневым, потому что только поддерево согласования только с одним ребенком будет истинным, но я думаю, что мое algo ниже аналогичного на ваш будет – Peter

+0

node = root; do { if (node-> noofchild) { node = node-> child [noofchild-1]; прочее { node-> parent-> noofchild -; curr = node-> parent; свободный (узел); node = curr; } } while (node-> parent || (node ​​== root && node)) – Peter

+1

Вы правы. Мой алгоритм работает только быстро ... У вашего алгоритма есть некоторые проблемы, например, если дерево пустое. Я бы использовал node = root; while (node) {if (node-> noofchild) {node-> noofchild--; node = node-> child [node-> noofchild]; } else {curr = node-> parent; свободный (узел); node = curr; }} – jofel