#include<iostream>
#include<stack>
#include<queue>
const int maxsize=100;
int index;//初始化树时的索引编号
using namespace std;
typedef char ElemType;
typedef struct BiNode{
ElemType data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
int CreateBiTree(BiTree &T,ElemType* pre)
{
index++;
if(pre[index]=='*') T=NULL;
else{
T=new BiNode;
T->data=pre[index];
CreateBiTree(T->lchild,pre);
CreateBiTree(T->rchild,pre);
}
return 1;
}
void visit(BiTree T)
{
cout<<T->data<<" ";
}
void PreOrder(BiTree T)
{
if(T){
visit(T);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BiTree T)
{
if(T){
InOrder(T->lchild);
visit(T);
InOrder(T->rchild);
}
}
void PostOrder(BiTree T)
{
if(T){
PostOrder(T->lchild);
PostOrder(T->rchild);
visit(T);
}
}
void InitBiTree(BiTree &T)
{//采用的是先跟插入到树里面,所有的空指针都要加上'*'
index=-1;
ElemType a[maxsize]={"abc**d**e**"};
CreateBiTree(T,a);
cout<<"the preorder of tree is: ";
PreOrder(T);
cout<<endl;
}
void InOrderLoop(BiTree T)
{//中序遍历循环策略
cout<<"the InorderLoop of tree is: ";
stack<BiTree> s;
BiTree p=T;
while(p||!s.empty()){
if(p){
s.push(p);
p=p->lchild;
}
else{
p=s.top();
s.pop();
visit(p);
p=p->rchild;
}
}
cout<<endl;
}
void LevelOrder(BiTree T){
//层序遍历遍历二叉树
cout<<"the Levelorder of tree is: ";
queue<BiTree> q;
BiTree p=T;
q.push(p);
while(!q.empty()){
p=q.front();
q.pop();
visit(p);
if(p->lchild){
q.push(p->lchild);
}
if(p->rchild){
q.push(p->rchild);
}
}
cout<<endl;
}
int main()
{
BiTree T;
InitBiTree(T);
InOrderLoop(T);
LevelOrder(T);
system("pause");
return 0;
}
为了简单化,栈和队列没有写,直接用的。本想把那个循环遍历的先序和后序写了,奈何能力有限,拿着那个中序循环遍历的程序翻过来覆过去还是没有写出来,遍历的乱七八糟的。谁如果有比较好的循环遍历的先序和后序代码,给贴一个,谢谢了。看着别人写的代码都挺好的,临着自己去写就犯二了,我还是低着头慢慢爬吧。。。