二叉树的非递归遍历中,前序和中序都比较简单。
Pre-sequence traversal
前序遍历只需要首先对每一个父节点输出,然后再处理左子,将左儿子压栈,由于是前序遍历压栈前都先输出该节点(弹栈的时候就不用输出,当然也不能在弹栈的时候输出),当最左子节点入栈后,开始通过弹栈处理右子节点,对于叶子节点或者没有右节点的子节点就不需要处理,对于每一个非空右子节点,其处理方式和根节点一样。总之就是压栈时处理左子节点,弹栈再处理右节点。
{ stack<BinTree*> s; BinTree *p=root; while(p!=NULL||!s.empty()) { while(p!=NULL) { cout<<p->data<<" "; s.push(p); p=p->lchild; } if(!s.empty()) { p=s.top(); s.pop(); p=p->rchild; } }}
Middle Sequence traversal
中序遍历和前序遍历的不同是,节点输出的顺序是,先左节点,然后父节点,最后右节点,相对前序遍历,只需要将压栈前输出节点改为每次弹栈时输出节点,其他一样。
{ stack<BinTree*> s; BinTree *p=root; while(p!=NULL||!s.empty()) { while(p!=NULL) { s.push(p); p=p->lchild; } if(!s.empty()) { p=s.top(); cout<<p->data<<" "; s.pop(); p=p->rchild; } } }
Post-post traversal
Solution One
The numbers represent the stacking order, after the left child node (7) into the stack, the top element of the stack is a leaf node, so you can directly output and stack it, then note the node just output (7), and then the top of the stack is (6), because the node (7) is not (6) son, also just output is not the son of the node, So the node does not eject, but the right child node, the left child node is pressed into the stack, and the same as before, until the leftmost child node is pressed into. At this time, such as the 8,9 are pressed into, (9) at the top of the stack, performing the same operation as before, when the 8 output and the stack, the top of the stack is (6), the node (6), just the output node (8) is its child nodes, so it can output (6). Always do this until there are no elements in the stack.
voidPostOrder3 (Bintree*Root//Non-recursive post-traversal{Stack<Bintree*>S Bintree*Cur//Current nodeBintree*Or:=NULL;//The node of the previous visitS.push (root); while(!S.Empty ()) {cur=S.Top ();if((cur -Lchild==NULL&&Cur -Rchild==NULL)||(Pre!=NULL&&(Pre==Cur -Lchild||Or:==Cur -Rchild))) {cout<<Cur -Data<<" ";//If the current node has no child nodes or if the child has been visitedS.Pop (); Or:=Cur }Else{if(cur -Rchild!=NULL) s.Push (cur -Rchild);if(cur -Lchild!=NULL) s.Push (cur -Lchild); } } }
Solution Two
In addition, a more intuitive approach can be used: However, the relative solution requires additional O (n) space complexity.
{ stack<BinTree*> s; stack<BinTree*> printS; s.push(root); BinTree* pCur; while(!s.empty()){ pCur = s.top(); s.pop(); printS.push(pCur); if(pCur->left != NULL) s.push(pCur->left); if(pCur->right != NULL) s.push(pCur->right); } while(!printS.empty()){ pCur = printS.top(); printS.pop(); cout << pCur->val << endl; } }
Binary tree non-recursive traversal