Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse tree without recursion and stack in C

How to traverse each node of a tree efficiently without recursion in C (no C++)?

Suppose I have the following node structure of that tree:

struct Node
{
    struct Node* next;   /* sibling node linked list */
    struct Node* parent; /* parent of current node   */
    struct Node* child;  /* first child node         */
}
  • It's not homework.
  • I prefer depth first.
  • I prefer no additional data struct needed (such as stack).
  • I prefer the most efficient way in term of speed (not space).
  • You can change or add the member of Node struct to store additional information.
like image 601
uray Avatar asked Jul 09 '10 15:07

uray


1 Answers

If you don't want to have to store anything, and are OK with a depth-first search:

process = TRUE;
while(pNode != null) {
    if(process) {
        //stuff
    }
    if(pNode->child != null && process) {
         pNode = pNode->child;
         process = true;
    } else if(pNode->next != null) {
         pNode = pNode->next;
         process = true;
    } else {
         pNode = pNode->parent;
         process = false;
    }
}

Will traverse the tree; process is to keep it from re-hitting parent nodes when it travels back up.

like image 169
zebediah49 Avatar answered Sep 22 '22 00:09

zebediah49