具体思想与括号转孩子数组法相同,只不过这里由指针方式实现
详见 http://blog.youkuaiyun.com/xinshoushanglu2333/article/details/49834531
#include<iostream>
#include<stack>
#include<cstring>
#define maxn 111111
#define m 3
using namespace std;
struct Tree
{
char data;
Tree *child[m];
Tree(){memset(child,0,sizeof(child));}//重载初始化都为空
};
Tree* convert(char s[],Tree *t)
{
int i =0 ;
Tree *root,*p,*q;
stack<Tree*>st;
p=root=new Tree();//先建立根节点
root->data=s[i];
i++;
do
{
//cout<<"s["<<i<<"] "<<s[i]<<endl;
if(s[i]=='(') st.push(p);//将上个元素的地址压入栈,遇到左括号
else if(s[i]==')') st.pop();
else if(s[i]>='a'&&s[i]<='z'||s[i]>='A'&&s[i]<='Z'||s[i]>='0'&&s[i]<='9')
{
p=new Tree();
p->data=s[i];
int k =0;
root=st.top();//弹出父节点
while(k<m&&root->child[k]!=NULL) k++;//找父节点存储儿子的指针域为空的空间
root->child[k]=p;//指向当前节点
}
i++;
}while(!st.empty());
return root;
}
void preorder(Tree *p)
{
if(p==NULL) return ;
cout<<p->data;
for(int i=0;i<m;i++)
preorder(p->child[i]);
}
void postorder(Tree *p)
{
if(p==NULL) return ;
for(int i=0;i<m;i++)
postorder(p->child[i]);
cout<<p->data;
}
int main()
{
Tree *t;
char s[maxn];
while(cin.getline(s,maxn))
{
t=convert(s,t);
preorder(t);
cout<<endl;
postorder(t);
}
return 0;
}