Three kinds of non-recursive traversal methods for binary tree

Source: Internet
Author: User

1. First Order traversal

1 voidpreordertraversal (bintree BT)2 {3 Bintree T;4Std::stack<bintree>Btstack;5T =BT;6      while(T | |!btstack.empty ())7     {8          while(T)9         {Ten Btstack.push (T); Oneprintf"%c", t->Data); AT = t->Left ; -         } -T =btstack.top (); the Btstack.pop (); -T = t->Right ; -  -     } +}

2. Middle Sequence traversal

1 voidinordertraversal (bintree BT)2 {3 Bintree T;4Std::stack<bintree>Btstack;5T =BT;6      while(T | |!btstack.empty ())7     {8          while(T)9         {Ten Btstack.push (T); OneT = t->Left ; A         } -T =btstack.top (); - Btstack.pop (); theprintf"%c", t->Data); -T = t->Right ; -  -     } +}

3. Post-Traversal (heavy difficulty)

Add a data field that represents the number of accesses in the structure node of the tree, visit:

1 typedef Position Bintree;    // two fork Tree type 2 struct tnode {3     ElementType Data;    // node Data 4     int visit; 5     Bintree left;        // point to left dial hand tree 6     Bintree right;        // point to the right sub-tree 7 };

traversing the Code program:

1 voidpostordertraversal (bintree BT)2 {3Bintree T =BT;4Std::stack<bintree>Btstack;5      while(T | |!btstack.empty ())6     {7          while(T)8         {9t->visit++;Ten Btstack.push (T); OneT = t->Left ; A         } -         if(!btstack.empty ()) -         { theT = Btstack.top ();//second or third visit to the node -          -             if(T->visit = =2)//when visit = = 2 o'clock, the node has been accessed 3 times, so it can be output -             { +printf"%c", t->Data); - Btstack.pop (); +T =NULL; A             } at             Else -             { -t->visit++;//Second Visit -T = t->right;//will be entering the third visit -             } -         } in     } -}

Three kinds of non-recursive traversal methods for binary tree

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.