/*
2018年11月12日
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<string>
using namespace std;
const int MAX_NODESIZE=1e5+7;
struct Node
{
char date;
int lchild;
int rchild;
Node()
{
lchild=rchild=-1;
}
} node[MAX_NODESIZE];
class Tree
{
public:
int root;
int top;//记录现在有多少个节点
string info;//因为每个数据是一个字符 所以所以这里直接用string类来存放遍历的信息
Tree()
{
root=0;
top=1;
info="";
}
void BulidTree()
{
bulidtree(0);//建造地址为0处的树
}
void ProOrder()//前序遍历树
{
info="";
proorder(root);
cout<<"ProOrder:"<<info<<endl;
}
void InOrder()
{
info="";
inorder(root);
cout<<"InOrder:"<<info<<endl;
}
void PostOrder()
{
info="";
postorder(root);
cout<<"postorder:"<<info<<endl;
}
private:
void bulidtree(int now)//递归建造树
{
node[now].lchild=node[now].rchild=-1;
char cc[2];
cout<<"Please input the info of node:";
scanf("%s",cc);
node[now].date=cc[0];
cout<<" Is Bulid left tree? :";
scanf("%s",cc);
if(cc[0]=='y')
{
node[now].lchild=top++;
bulidtree(top-1);
}
cout<<" Is Bulid right tree? :";
scanf("%s",cc);
if(cc[0]=='y')
{
node[now].rchild=top++;
bulidtree(top-1);
}
}
void proorder(int now)
{
info+=node[now].date;
if(~node[now].lchild)
{
proorder(node[now].lchild);
}
if(~node[now].rchild)
{
proorder(node[now].rchild);
}
}
void inorder(int now)
{
if(~node[now].lchild)
{
inorder(node[now].lchild);
}
info+=node[now].date;
if(~node[now].rchild)
{
inorder(node[now].rchild);
}
}
void postorder(int now)
{
if(~node[now].lchild)
{
postorder(node[now].lchild);
}
if(~node[now].rchild)
{
postorder(node[now].rchild);
}
info+=node[now].date;
}
//前序遍历二叉树
//中序遍历树
//后序遍历树
};
int main()
{
Tree dchOfTree;
dchOfTree.BulidTree();
dchOfTree.ProOrder();
dchOfTree.InOrder();
dchOfTree.PostOrder();
}
代码已经过调试。