Uva 536 前序中序序列构建树

本文介绍了一种使用map容器存储树的方法来求解后序遍历问题,详细阐述了从中序遍历和前序遍历序列构建树的过程,并展示了通过递归调用来实现后序遍历的代码实现。

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

原题

由中序遍历和前序遍历序列求树的后序
题目虽然简单但是确实比较经典, 所以还是记录一下吧
这次尝试一下用map容器存储树
这样既能表面上实现树的顺序存储, 又不会浪费太多空间 :)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <list>
#include <cassert>
#include <iomanip>

#pragma warning(disable:4996) //关掉4996警告

/*
Uva 536

*/

using namespace std;

map<int, char> Tree;            // 尝试用map存储树

void Build(const char * pre, const char * inorder, int root, int N) {
    if ( N == 0 ) return;
    Tree[root] = *pre;
    int tmp = 0;
    while ( inorder[tmp] != Tree[root] ) tmp++;
    Build(pre + 1, inorder, root * 2, tmp);
    Build(pre + tmp + 1, inorder + tmp + 1, root * 2 + 1, N - tmp - 1);
}

void PostTrav(int node) {
    if ( Tree[node * 2] )     PostTrav(node * 2);
    if ( Tree[node * 2 + 1] ) PostTrav(node * 2 + 1);
    cout << Tree[node];
}

int main( ) {
    //freopen("input.txt", "r", stdin);
    string pre, inorder;
    while ( cin >> pre ) {
        cin >> inorder;
        Tree.clear( );
        Build(pre.c_str(), inorder.c_str(), 1, pre.length());
        PostTrav(1);
        cout << endl;
    }
    //system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值