二叉树的非递归遍历中,前序和后续基本一致,比较简单,后续非递归遍历稍微复杂些,需要判断是从左子树返回还是右子树返回,代码如下:
#include <iostream> #include <stack> #include <string> struct treeNode{ treeNode*lChild; treeNode*rChild; char data; }; typedef treeNode* biTree; const char deli='^'; /*using preOrderTraverse to create binary tree*/ void createTree(biTree& pTree){ char c=deli; std::cin>>c; if(c==deli){ pTree=NULL; return; } pTree=new treeNode; pTree->data=c; createTree(pTree->lChild); createTree(pTree->rChild); } void visit(biTree pNode){ if(pNode==NULL) ;//std::cout<<deli; else std::cout<<pNode->data; }
/*前序递归遍历,用于对比*/ void preOrderTraverse(biTree pTree,void(*v)(biTree pNode)){ v(pTree); if(!pTree){ return; } preOrderTraverse(pTree->lChild,v); preOrderTraverse(pTree->rChild,v); }
/*后续非递归*/ void postOrderTraverse(biTree pTree,void(*v)(biTree pNode)){ biTree p=pTree; std::stack<biTree> s; if(!p) return; s.push(p); while(p->lChild){ p=p->lChild; s.push(p); } p=s.top(); s.pop(); visit(p); biTree T; while(!s.empty()){ T=s.top(); s.pop(); if(T->lChild==p){ if(T->rChild){ s.push(T); T=T->rChild; s.push(T); while(T->lChild){ T=T->lChild; s.push(T); } p=s.top(); s.pop(); v(p); }else{ v(T); p=T; } }else if(T->rChild==p){ v(T); p=T; } } }
int main(int argc,char**argv){ biTree pTree; createTree(pTree); preOrderTraverse(pTree,visit); std::cout<<std::endl; postOrderTraverse(pTree,visit); std::cout<<std::endl; }前序建立二叉树的测试用例:
abdf^^^egi^^^h^^c^^