UVA 536 二叉树还原

题意

一棵二叉树由 ABC...XYZ来代表节点表示

现在,给予先序遍历和中序遍历,还原树,输出后序遍历

Sample Input

DBACEGF ABCDEFG

BCAD CBAD

Sample Output

ACBFGED

CDAB

思路 基本树还原,边还原边输出树


WA 1

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <sstream>
#include <string>
#define maxn 30
using namespace std;
struct node{
    int r,l;
}tree[maxn];
    string s1,s2;
int build(int l1,int r1, int l2, int r2){
    if(l1>r1)
        return 0;
    int root=s1[l1]-'A'+1;
    int len=0;
    for(int i = l2 ; i<=r2 ; i++){
        if(s1[l1]==s2[i])
            break;
        len++;
    }
    tree[root].l=build(l1+1,l1+len,l2,l2+len-1);
    tree[root].r=build(l1+1+len,r1,l2+len+1,r2);
}
int dfs(int x){
    if(tree[x].l)
        dfs(tree[x].l);
    if(tree[x].r)
        dfs(tree[x].r);
    printf("%c",x+'A'-1);
}
int main(){
    while(cin>>s1>>s2){
        int n = s1.size();
        build(0,n-1,0,n-1);
        int root=s1[0]-'A'+1;
        dfs(root);
        printf("\n");
    }
}
到现在都还是没能够找到错误,dfs后序遍历没问题啊,uDebug上也没出问题

后来 讲建树与输出改在一起了,就ac了

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <sstream>
#include <string>
#define maxn 30
using namespace std;
struct node{
    int r,l;
}tree[maxn];
    string s1,s2;
int build(int l1,int r1, int l2, int r2){
    if(l1>r1)
        return 0;
    int root=s1[l1]-'A'+1;
    int len=0;
    for(int i = l2 ; i<=r2 ; i++){
        if(s1[l1]==s2[i])
            break;
        len++;
    }
    tree[root].l=build(l1+1,l1+len,l2,l2+len-1);
    tree[root].r=build(l1+1+len,r1,l2+len+1,r2);
    printf("%c",s1[l1]);
}
int main(){
    while(cin>>s1>>s2){
        int n = s1.size();
        build(0,n-1,0,n-1);
        printf("\n");
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值