还原二叉树

389 篇文章 1 订阅
8 篇文章 0 订阅

还原二叉树
Case Time Limit: 100 MS (Others) / 200 MS (Java) Case Memory Limit: 256 MB (Others) / 512 MB (Java)
Accepted: 186 Total Submission: 262

Problem Description
给一棵二叉树的层序遍历序列和中序遍历序列,求这棵二叉树的先序遍历序列和后序遍历序列。
Input
每个输入文件中一组数据。

第一行一个正整数N(1<=N<=30),代表二叉树的结点个数(结点编号为1~N)。接下来两行,每行N个正整数,分别代表二叉树的层序遍历序列和中序遍历序列。数据保证序列中1~N的每个数出现且只出现一次。
Output
输出两行,每行N个正整数,分别代表二叉树的先序遍历序列和后序遍历序列。每行末尾不输出额外的空格。
Sample Input
7

3 5 4 2 6 7 1

2 5 3 6 4 7 1
Sample Output
3 5 2 4 6 7 1

2 5 6 1 7 4 3
Author
Shoutmon
Source
15浙大考研机试模拟赛

主要在于用中序和层序建树,首先来说,第一个层序的节点,一定是根节点,而中序可以把序列分开为根的左右分支,假设中序的序列的下标为InL, InR, 则从左往右遍历层序的节点,第一次找到在InL至InR之间的存在值与当前中序的的值相同,那么这个节点就是当前的根节点,中序值又将其分为左右两个序列,循环建树即可,实现见代码

#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <queue>
#include <map>

using namespace std;
const int MaxN = 36;
int n = 0;
int le[MaxN], in[MaxN];
typedef struct tnode{
    int data;
    struct tnode * lchild;
    struct tnode * rchild;
    tnode() { lchild = rchild = nullptr; }
}TNode, *PTNode;


PTNode CreateTree(int il,int ir) {
    if (il > ir) return nullptr;
    int leidx = 0, idx = il;
    for (; leidx < n; ++leidx) {
        idx = il; bool flag = false;
        while (idx <= ir) {
            if (le[leidx] == in[idx]) {
                flag = true;
                break;
            }
            ++idx;
        }
        if (flag)break;
    }

    PTNode node = new TNode;
    node->data = le[leidx];
    node->lchild = CreateTree(il, idx - 1);
    node->rchild = CreateTree(idx + 1, ir);
    return node;
}

int pidx = 0;
void pre(PTNode root) {
    if (!root)return;
    cout << root->data;
    if (++pidx != n)cout << " ";
    pre(root->lchild);
    pre(root->rchild);
}

int idx = 0;
void post(PTNode root) {
    if (!root)return;
    post(root->lchild);
    post(root->rchild);
    cout << root->data;
    if (++idx != n)cout << " ";
}


int main() {
#ifdef _DEBUG
    freopen("data.txt", "r+", stdin);
#endif // _DEBUG
    std::ios::sync_with_stdio(false);

    PTNode root;
    cin >> n;
    for (int i = 0; i < n; ++i)cin >> le[i];
    for (int i = 0; i < n; ++i)cin >> in[i];
    root = CreateTree(0, n - 1);
    pre(root);
    cout << endl;
    post(root);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值