Non-recursive traversal of Binary Trees

Source: Internet
Author: User

Non-recursive traversal of Binary Trees

First-order traversal

 

Void PreOrder_Nonrecursive1 (BiTree T) // non-recursive {if (! T) return; stack
 
  
S; BiTree curr = T; while (curr! = NULL |! S. empty () {while (curr! = NULL) {cout <
  
   
Data <; s. push (curr); curr = curr-> lchild;} if (! S. empty () {curr = s. top (); s. pop (); curr = curr-> rchild ;}}}
  
 

Sequential Traversal

 

 

Void InOrderTraverse1 (BiTree T) // non-recursive {if (! T) return; BiTree curr = T; // point to the node stack to be checked
 
  
S; while (curr! = NULL |! S. empty () {while (curr! = NULL) {s. push (curr); curr = curr-> lchild;} // while if (! S. empty () {curr = s. top (); s. pop (); cout <
  
   
Data <; curr = curr-> rchild ;}}}
  
 
Post-order traversal:

 

 

Void PostOrder_Nonrecursive (BiTree T) // non-recursive double stack method for post-sequential traversal {stack
 
  
S1, s2; BiTree curr; // point to the current node s1.push (T); while (! S1.empty () // end when stack is empty {curr = s1.top (); s1.pop (); s2.push (curr); if (curr-> lchild) s1.push (curr-> lchild); if (curr-> rchild) s1.push (curr-> rchild);} while (! S2.empty () {printf (% c, s2.top ()-> data); s2.pop ();}}
 


 

 

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.