Preamble non-recursive traversal (borrow stack structure):
① the root stack;
② sentence stack space, access to the top element output;
③ to determine whether the right subtree is empty, and then determine whether the left subtree is empty, back to ② executed.
void PreOrder(BinTree bt) { stack<BinTree> astack; BinTreeNode * p; astack.push(bt); while(!astack.empty()) { p=astack.top(); astack.pop(); cout<<p->data<<" "; if(p->rightchild!=NULL) { astack.push(p->rightchild); } if(p->leftchild!=NULL) { astack.push(p->leftchild); } } }
In order non-recursive traversal (borrow stack structure):
First root stack
① First, save the current node all the left tree node;
② When the tree is left empty, get the top element (leftmost subtree) output val;
③ then access right subtree top element (p = p-> right), fall back to ①.
void the InOrder (BinTree BT) { Stack <BinTree> aStack; BinTree P; P = BT; IF (P == NULL) { return ; } astack.push (BT); P = p-> leftchild; the while (P || ! astack.empty ()) { the while (P = NULL)! // along the left branch of the depth until a NULL { astack.push (P); P = p-> leftchild; } P = astack.top (); // pop up one by one, visit astack.pop (); COUT << p-> Data << " " ; P = p-> rightchild; // into the right branch, the next circle, on the right branch of the left depth } }
Postorder traversal non-recursive (borrow stack structure):
① determines whether the current node is not empty, and the stack is not empty, then the left subtree of the root node of all nodes push.
② get the top element and pop (), this time to determine what the top element of the left subtree, whether it is the last pop out of the elements (ie "/" type, represents the current top element of the right sub-tree traversal yet , so again the right subtree of the root node of the current top of the stack), continue ①; not satisfied, it is to NULL.
void postorder (BinTree BT) { BinTree P = BT; Stack <BinTree> aStack; IF (BT == NULL) { return ; } the while (!! = NULL || P astack.empty ()) { the while ! (P = NULL) { astack.push (the p-); the p- = p-> p-leftchild> leftchild:? p-> rightchild; // if the left child is not empty, the children move to the left, or move to the right child } // here We have reached the bottom P = astack.top (); astack.pop (); COUT << p-> << Data" " ; IF - (astack.empty () && (astack.top ()> leftchild the p-==)!) // If the stack is not empty, and just access node is left child of { the p- = astack.top () - > rightchild; // shift to the right child, the next big cycle began looking for the bottom of this node } the else // if the child is the right, indicating that the child was left in the last process { the p- = NULL; // the p-Fu is empty , so that the next cycle of the first cycle was passing large, corresponding to the returned one } } }