Description
给出树的前序遍历及中序遍历,求其后序遍历。
Input
存在多组数据,请做到文件底结束
每组数据给出两个字符串,均不超过26个字母。分为前序、中序遍历。
每组数据给出两个字符串,均不超过26个字母。分为前序、中序遍历。
Output
如题
Sample Input
DBACEGF ABCDEFG
BCAD CBAD
Sample Output
ACBFGED
CDAB
HINT
Source
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
struct node
{
char value;
node *lchild,*rchild;//左右子树
};
node *newnode(char c)
{
node *p;
p=(node *)malloc(sizeof(node));
p->value=c;
p->lchild=p->rchild=NULL;
return p;
}
node *rebulid(char *pre,char *in,int n)
{
if(n==0) return NULL;
int l_len,r_len,i;
char s=pre[0];
node *root=newnode(s);
for(i=0;i<n&&in[i]!=s;i++);
l_len=i;
r_len=n-i-1;
if(l_len>0) root->lchild=rebulid(pre+1,in,l_len);//递归求解
if(r_len>0) root->rchild=rebulid(pre+l_len+1,in+l_len+1,r_len);
return root;
}
void postorder(node *p)
{
if(p==NULL) return;
postorder(p->lchild);
postorder(p->rchild);
printf("%c",p->value);
}
int main()
{
char preorder[30],inorder[30];
while(scanf("%s%s",preorder,inorder)!=EOF)
{
node *root=rebulid(preorder,inorder,strlen(preorder));
postorder(root);
printf("\n");
}
return 0;
}
已知后序和中序,求前序
#include <cstdio>
#include <cstring>
#include <cstdlib>
struct node
{
char value;
node *lchild,*rchild;//左孩子,右孩子
};
node *newnode(char c)
{
node *p=(node *)malloc(sizeof(node));
p->value=c;
p->lchild=p->rchild=NULL;
return p;
}
node *rebulid(char *post,char *in,int n)
{
if(n==0) return NULL;
char ch=post[n-1];//得到的是根节点的值
node *p=newnode(ch);
int i;
for(i=0;i<n&&in[i]!=ch;i++);
int l_len=i;
int r_len=n-i-1;
if(l_len>0) p->lchild=rebulid(post,in,l_len);//由中序遍历得出左右子树的值
if(r_len>0) p->rchild=rebulid(post + l_len, in+l_len+1, r_len);
return p;
}
void preorder(node *p)//先序遍历
{
if(p==NULL) return;
printf("%c",p->value);
preorder(p->lchild);
preorder(p->rchild);
}
int main()
{
char postorder[30],inorder[30];
while(scanf("%s%s",postorder,inorder)!=EOF)
{
node *root=rebulid(postorder,inorder,strlen(postorder));
preorder(root);
printf("\n");
}
return 0;
}