poj-2255-Tree Recovery(tree)

本文介绍了一种根据给定的前序和中序遍历序列构建二叉树,并求解后序遍历序列的方法。通过递归地寻找根节点,并以此划分左右子树,最终实现了从输入序列到后序遍历输出的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值