根据先序,中序,求后序遍历#include<cstdio> #include<cstring> #include<iostream> using namespace std; struct Node { char data; Node *lchild,*rchild; }; Node* createtree(string pre,string in) { Node *root=NULL
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
struct Node
{
char data;
Node *lchild,*rchild;
};
Node* createtree(string pre,string in)
{
Node *root=NULL;
if(pre.length()>0)
{
root=new Node;
root->data=pre[0];
int index=in.find(root->data);
root->lchild=createtree(pre.substr(1,index),in.substr(0,index));
root->rchild=createtree(pre.substr(index+1),in.substr(index+1));
}
return root;
}
void posorder(Node *root)
{
if(root!=NULL)
{
posorder(root->lchild);
posorder(root->rchild);
cout<<root->data;
}
}
int main()
{
string pre_str,in_str;
Node *root;
printf("请输入二叉树的先序序列换行后输入中序序列\n");
while(cin>>pre_str>>in_str)
{
root=createtree(pre_str,in_str);
posorder(root);
cout<<endl;
}
return 0;
}