Traverse tree without recursion and stack in C

后端 未结 5 1222
日久生厌
日久生厌 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 22:10

    This looks like an exercise I did in Engineering school 25 years ago. I think this is called the tree-envelope algorithm, since it plots the envelope of the tree.

    I can't believe it is that simple. I must have made an oblivious mistake somewhere. Any mistake regardless, I believe the enveloping strategy is correct. If code is erroneous, just treat it as pseudo-code.

    while current node exists{
      go down all the way until a leaf is reached;
      set current node = leaf node;
      visit the node (do whatever needs to be done with the node);
    
      get the next sibling to the current node;
      if no node next to the current{
        ascend the parentage trail until a higher parent has a next sibling;
      }
      set current node = found sibling node;
    }
    

    The code:

    void traverse(Node* node){
    
      while(node!=null){
        while (node->child!=null){
          node = node->child;
        }
    
        visit(node);
    
        node = getNextParent(Node* node);
      }
    }
    
    /* ascend until reaches a non-null uncle or 
     * grand-uncle or ... grand-grand...uncle
     */
    Node* getNextParent(Node* node){
    
      /* See if a next node exists
       * Otherwise, find a parentage node
       * that has a next node
       */
      while(node->next==null){
        node = node->parent;
        /* parent node is null means
         * tree traversal is completed
         */
        if (node==null)
          break;
      }
    
      node = node->next;
    
      return node;
    }
    

提交回复
热议问题