【ZOJ 1944】 Tree Recovery

Description

给出树的前序遍历及中序遍历,求其后序遍历。

Input

存在多组数据,请做到文件底结束
每组数据给出两个字符串,均不超过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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值