Tree Recovery (UVa 536) 递归遍历二叉树

题目:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=839&page=show_problem&problem=477

思路:根据先序遍历和中序遍历建树,再输出下后序遍历即可

/* Tree Recovery (UVa 536) */
#include <iostream>
#include <cstring>
using namespace std;

const int maxn = 30;

char preOrder[maxn], inOrder[maxn];        //先序遍历、中序遍历 
char lch[maxn], rch[maxn];                //左结点、右结点

char build(int L1, int R1, int L2, int R2);
void output(char c);

int main(){
    //freopen("input.txt", "r", stdin);
    while(cin >> preOrder >> inOrder){
        memset(lch, 0, sizeof(lch));
        memset(rch, 0, sizeof(rch));
        build(0, strlen(preOrder)-1, 0, strlen(inOrder)-1);
        output(preOrder[0]);
        cout << endl;
    }
    return 0;
}

char build(int L1, int R1, int L2, int R2){
    if(L1 > R1 || L2 > R2)
        return 0;
    int mid;
    for(int i=L2; i<=R2; i++){
        if(inOrder[i] == preOrder[L1]){
            mid = i;
            break;
        }
    }
    
    lch[preOrder[L1]-'A'] = build(L1+1, L1+(mid-L2), L2, mid-1);
    rch[preOrder[L1]-'A'] = build(L1+(mid-L2)+1, L1-L2+R2, mid+1, R2);
    
    return preOrder[L1];
}

void output(char c){
    if(c == 0)
        return ;
    int index = c - 'A';
    output(lch[index]);
    output(rch[index]);
    
    cout << c;    
}

 

posted @ 2016-11-03 21:46  淡蓝色光  阅读(165)  评论(0编辑  收藏  举报