第一天PAT-A1020 Tree Traversals

27 篇文章 0 订阅

A1020

Description:

假设二叉树中的key都是不同的正整数,给出后序和中序遍历序列,求这棵树的层次遍历序列

Input:

  • 一个测试一组样例
  • 首行正整数N<=30,代表二叉树中所有的数字节点个数
  • 第二行给出后序序列,第三行给出中序序列
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Output:

对于每个测试样例,输出一行层次遍历序列,数字由空格隔开

4 1 6 3 5 7 2

算法构思:

关键是根据后序序列(左右根)和中序序列(左根右)特性构建二叉树,代码不难:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 35;

struct Node{
    int data;
    Node* lchild;   //左子树
    Node* rchild;   //右子树
};

Node* CreateNode(int n){
    Node* anode = new Node;
    anode->data = n;
    anode->lchild = nullptr;
    anode->rchild = nullptr;
    return anode;
}

int n;
int pre[maxn], in[maxn], post[maxn];   //前序, 中序, 后序
map<int, int>postIndex; //返回后序序列中的位置
map<int, int>inIndex;   //返回中序序列中的位置
Node* BinaryTree = nullptr;

Node* constructTree(int postL, int postR, int inL, int inR){
    if(postL > postR)
        return nullptr;
    int rootDa = post[postR];
    Node* root = CreateNode(rootDa);
    int rnum = inR - inIndex[rootDa];
    int lnum = inIndex[rootDa] - inL;
    root->rchild = constructTree(postR-rnum, postR-1, inIndex[rootDa]+1, inIndex[rootDa]+rnum);
    root->lchild = constructTree(postL, postL+lnum-1, inL, inIndex[rootDa]-1);
    return root;
}

void BFS(){
    queue<Node*>ans;
    ans.push(BinaryTree);
    printf("%d", ans.front()->data);
    while(!ans.empty()){
        Node* now = ans.front();
        if(now->lchild != nullptr) ans.push(now->lchild);
        if(now->rchild != nullptr) ans.push(now->rchild);
        if(now != BinaryTree) printf(" %d", now->data);
        ans.pop();
    }
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d", &post[i]);
        postIndex.insert(pair<int, int>(post[i], i));
    }
    for(int i = 0; i < n; i++){
        scanf("%d", &in[i]);
        inIndex.insert(pair<int, int>(in[i], i));
    }
    BinaryTree = constructTree(0, n-1, 0, n-1);
    BFS();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值