Hoj 1452 Tree Recovery

题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=1452

题意:已知中序表达式和先序表达式求后序表达式。

我们知道先序、中序、后序、层序这四种遍历方式中,只要有中序和其他任意一种顺序,即可构建这个二叉树。并且求得其他的顺序。

方法一:一步到位

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;

char pre[30];
char in[30];

void findPost(int root,int left,int right)
{
    if(left>right)
        return;
    int i;
    //left,right是针对于中缀表达式的
    for(i = left;i<=right;i++)
    {
        if(in[i] == pre[root])
        {
            break;
        }
    }
    //in[i]是根节点
    findPost(root+1,left,i-1);
    findPost(root + 1 + i - left,i+1,right);
    printf("%c",in[i]);
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    while(scanf(" %s %s",pre,in)!=EOF)
    {
        findPost(0,0,strlen(in)-1);
        printf("\n");
    }
}

方法二:构建好二叉树后,再后序遍历。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;

char pre[30];
char in[30];

struct Tree
{
    Tree * lch;
    Tree * rch;
    char data;
};
//注意root要取地址。
void build_tree(Tree * &root,int index,int left,int right)
{
    if(left>right)
        return;
    if(root == NULL)
    {
        root = new Tree;
        root->rch = NULL;
        root->lch = NULL;
        root->data = pre[index];
    }
    int i;
    for(i = left;i<=right;i++)
    {
        if(pre[index] == in[i])
        {
            break;
        }
    }
    build_tree(root->lch,index + 1,left,i-1);
    build_tree(root->rch,index + 1 + i - left,i+1,right);
}
void findPost(Tree * root)
{
    if(root == NULL)
        return;
    findPost(root->lch);
    findPost(root->rch);
    printf("%c",root->data);
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    while(scanf(" %s %s",pre,in)!=EOF)
    {
        Tree * root = NULL;
        build_tree(root,0,0,strlen(in)-1);
        findPost(root);
        printf("\n");
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值