// Preordered travel tree or its subtree template <class T> void binarytree <t>: Preorder (binarytreenode <t> * root) {stack <binarytreenode <t> *> astack; binarytreenode <t> * pointer = root; while (! Astack. empty () | pointer) {If (pointer) {// access the current node visit (pointer); // access the current node address to the stack astack. push (pointer); // The current link structure points to the left child pointer = pointer-> leftchild ();} else {// The left subtree has been accessed, turn to access the right subtree pointer = astack. top (); astack. pop (); // stack top element rollback // The current link structure points to the right child pointer = pointer-> rightchild ();}} // end while} // The middle-order travel binary tree or its sub-tree template <class T> void binarytree <t>: inorder (binarytreenode <t> * root) {stack <binarytreenode <t> *> astack; binarytreenode <t> * Poin TER = root; while (! Astack. empty () | pointer) {If (pointer) {// the current node address is added to the stack astack. push (pointer); // The current link structure points to the left child pointer = pointer-> leftchild ();} // end ifelse {// The left subtree has been accessed, turn to access the right subtree pointer = astack. top (); astack. pop (); // stack top element rollback visit (pointer); // access the current node // The current link structure points to the right child pointer = pointer-> rightchild ();} // end else} // end while} // The back-order travel binary tree or its subtree template <class T> void binarytree <t >:: postorder (binarytreenode <t> * root) {// use the STL stack part Using STD: Stack; stackeleme NT <t> element; // stack declaration stack <stackelement <t> astack; binarytreenode <t> * pointer; If (root = NULL) return; // empty tree returns // else pointer = root; while (true) {// enter the left subtree while (pointer! = NULL) {element. pointer = pointer; element. tag = left; astack. push (element); // travel down the left subtree to pointer = pointer-> leftchild ();} // push out the top element of the stack = astack. top (); astack. pop (); pointer = element. pointer; // return from the right subtree while (element. tag = right) {visit (pointer); // access the current node if (astack. empty () return; // else {element = astack. top (); astack. pop (); // poll the stack pointer = element. pointer; //} // end else} // end while // element returned from the left subtree. tag = right; astack. push (element); // redirect to access the right subtree pointer = pointer-> rightchild ();} // end while}
reference (Beijing University instructor Zhang Ming ppt)