输入为:abd##eh###cfi##j##g##
1、普通层序遍历:输出为一行
2、进阶版1:输出每一层,从左向右依次输出
3、进阶版2:S型输出每一层,即从右向左和从左向右交替输出
#include<iostream> #include<vector> using namespace std; template<class T> struct BiNode { T data; BiNode<T>* leftchild,*rightchild; }; template<class T> class BiTree { public: BiTree(); BiNode<T>* GetRoot(); void PreOrder(BiNode<T>* node); void LevelOrder1(BiNode<T>* node);//层次遍历 void LevelOrder2(BiNode<T>* node);//高级版层序遍历 void LevelOrder3(BiNode<T>* node);//螺旋版层序遍历 private: BiNode<T>* m_root; BiNode<T>* Create(); }; template<class T> BiNode<T>* BiTree<T>::GetRoot() { return m_root; } template<class T> BiTree<T>::BiTree() { m_root = new BiNode<T>; m_root = Create(); } template<class T> BiNode<T>* BiTree<T>::Create() { char ch; cin>>ch; BiNode<T>* pnode; if (ch == '#') pnode = NULL; else { pnode = new BiNode<T>; pnode->data = ch; pnode->leftchild = Create(); pnode->rightchild = Create(); } return pnode; } /*template<class T> void BiTree<T>::PreOrder(BiNode<T>*R){ if(R){ cout<<R->data<<' '; PreOrder(R->leftchild); PreOrder(R->rightchild); } }*/ template<class T> void BiTree<T>::LevelOrder1(BiNode<T>* R){//普通版 BiNode<T> * queue[100]; BiNode<T> * p; int f=0,r=0; if(R) queue[++r]=R; while(f!=r){ p=queue[++f]; cout<<p->data; if(p->leftchild) queue[++r]=p->leftchild; if(p->rightchild) queue[++r]=p->rightchild; } } template<class T> void BiTree<T>::LevelOrder2(BiNode<T>* R){//进阶版1 if(R){ vector<BiNode<T> *> vec; vec.push_back(R); int f=0,r=1; while(f<vec.size()){ r=vec.size(); while(f<r){ cout<<vec[f]->data<<' '; if(vec[f]->leftchild) vec.push_back(vec[f]->leftchild); if(vec[f]->rightchild) vec.push_back(vec[f]->rightchild); f++; } cout<<endl; } } } template<class T> void BiTree<T>::LevelOrder3(BiNode<T>* R){//进阶版2 if(R){ vector<BiNode<T> *> vec; vec.push_back(R); int f=0,r=1,s=1; int check=0; while(f<vec.size()){ r=vec.size(); check=1-check; int r1=r; while(f<r1){ if(check){ cout<<vec[f]->data<<' '; if(vec[r-1]->rightchild){ vec.push_back(vec[r-1]->rightchild);} if(vec[r-1]->leftchild){ vec.push_back(vec[r-1]->leftchild);} f++; r--;} else{ cout<<vec[f]->data<<' '; if(vec[r-1]->leftchild){ vec.push_back(vec[r-1]->leftchild);} if(vec[r-1]->rightchild){ vec.push_back(vec[r-1]->rightchild);} f++; r--; } } cout<<endl; } } } int main() { BiTree<char> mtree; //cout<<"PreOrder:"<<endl; BiNode<char> *root=mtree.GetRoot(); //mtree.PreOrder(root); cout<<"LevelOrder:"<<endl; mtree.LevelOrder3(root); system("pause"); return 0; }
原文:http://blog.csdn.net/eliza1130/article/details/44418527