poj-2255-Tree Recovery(tree)

来源:互联网 发布:2016网络大型游戏 编辑:程序博客网 时间:2024/06/03 14:03

题目地址

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 3500using 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;}
原创粉丝点击