poj-2255-Tree Recovery(tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33096883/article/details/77606695

题目地址

http://poj.org/problem?id=2255

题目大意

  • 给出前序和中序序列,求后续遍历

Code

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <queue>
#include <map>
#include <vector>
#include <math.h>
#include <algorithm>
#define INF 0x3fffffff
#define N 3500

using namespace std;
typedef long long LL;

struct Node {
    char v;
    Node *l;
    Node *r;
    Node() {
        l = NULL;
        r = NULL;
    }
};

char before[128];
char mid[128];

Node* build_tree(char *before, char *mid, int len) {
    if (len == 0) return NULL;
    char c = before[0];
    int pos = 0;
    while (mid[pos] != c) {
        pos++;
    }
    Node *node = new Node();
    node->v = c;
    node->l = build_tree(before+1, mid, pos);
    node->r = build_tree(before+pos+1, mid+pos+1, len-pos-1);
    return node;
}

void print_back(Node *node) {
    if (node->l != NULL) {
        print_back(node->l);
    }
    if (node->r != NULL) {
        print_back(node->r);
    }
    if (node != NULL) {
        printf("%c", node->v);
    }
}

int main() {

#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#else
    //
#endif


    while (cin >> before >> mid) {
        Node* root = build_tree(before, mid, strlen(before));
        print_back(root);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33096883/article/details/77606695
今日推荐