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