poj-2255-Tree Recovery(tree)
阿新 • • 發佈:2018-11-06
題目地址
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;
}