Binary tree traversal non-recursion

Source: Internet
Author: User

Original http://www.wangchao.net.cn/bbsdetail_66513.html

 

1. Traverse non-Recursive Algorithms in sequence
# Define Max size 100
Typedef struct
{
Bitree Elem [maxsize];
Int top;
} SqStack;
Void PreOrderUnrec (Bitree t)
{
SqStack s;
StackInit (s );
P = t;
  
While (p! = Null |! StackEmpty (s ))
{
While (p! = Null) // traverse the left subtree
{
Visite (p-> data );
Push (s, p );
P = p-> lchild;
} // Endwhile
  
If (! StackEmpty (s) // uses the embedded while in the next loop to implement the right subtree Traversal
{
P = pop (s );
P = p-> rchild;
} // Endif
  
} // Endwhile
  
} // PreOrderUnrec
2. Non-recursive algorithm for sequential Traversal
# Define Max size 100
Typedef struct
{
Bitree Elem [maxsize];
Int top;
} SqStack;
Void InOrderUnrec (Bitree t)
{
SqStack s;
StackInit (s );
P = t;
While (p! = Null |! StackEmpty (s ))
{
While (p! = Null) // traverse the left subtree
{
Push (s, p );
P = p-> lchild;
} // Endwhile
  
If (! StackEmpty (s ))
{
P = pop (s );
Visite (p-> data); // access the root node
P = p-> rchild; // use the next loop to traverse the right subtree
} // Endif
  
} // Endwhile
} // InOrderUnrec
3. Post-order traversal of non-Recursive Algorithms
# Define Max size 100
Typedef enum {L, R} tagtype;
Typedef struct
{
Bitree ptr;
Tagtype tag;
} Stacknode;
Typedef struct
{
Stacknode Elem [maxsize];
Int top;
} SqStack;
Void PostOrderUnrec (Bitree t)
{
SqStack s;
Stacknode x;
StackInit (s );
P = t;
  
Do
{
While (p! = Null) // traverse the left subtree
{
X. ptr = p;
X. tag = L; // mark as left subtree
Push (s, x );
P = p-> lchild;
}
  
While (! StackEmpty (s) & s. Elem [s. top]. tag = R)
{
X = pop (s );
P = x. ptr;
Visite (p-> data); // The tag is R, indicating that the access to the right subtree is complete, so the access to the root node
}
  
If (! Stackempty (s ))
{
S. ELEM [S. Top]. Tag = r; // traverse the right subtree
P = S. ELEM [S. Top]. PTR-> rchild;
}
} While (! Stackempty (s ));
} // Postorderunrec

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.