Traverse tree without recursion and stack in C

后端 未结 5 1218
日久生厌
日久生厌 2021-02-05 21:38

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
{
         


        
5条回答
  •  温柔的废话
    2021-02-05 21:56

    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.

提交回复
热议问题