PAT甲级 1020 Tree Traversals 二叉树的中序,后序转层次遍历

39 篇文章 0 订阅

在这里插入图片描述

题意:

给出一棵二叉树的后序遍历序列和中序遍历序列,求这棵二叉树的层序遍历序列。

思路:

可以先参考:
前序、中序转后序
后序、中序转前序

后序、中序转层序与后序、中序转前序差不多,主要是我们需要一个index来记录层次遍历中结点的序号。

代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int post[35];//后序序列
int in[35];//中序序列
int n;//结点个数
int cnt=0;

struct node{
  int index;
  int key;
}level[35];

bool cmp(node a,node b){
  return a.index<b.index;
}

void level_output(int root,int start,int ends,int index){//层序打印
  if(start>ends){
    return;
  }
  int i=start;
  while(i<ends&&in[i]!=post[root]){//找到中序序列中根结点的位置
    i++;
  }
  level[cnt].key=post[root];
  level[cnt].index=index;
  cnt++;
  level_output(root-(ends-i+1),start,i-1,2*index+1);//遍历左子树
  level_output(root-1,i+1,ends,2*index+2);//遍历右子树
}

int main(){
  cin>>n;
  for(int i=0;i<n;i++){//读入后序序列
    cin>>post[i];
  }
  for(int i=0;i<n;i++){
    cin>>in[i];
  }
  level_output(n-1,0,n-1,0);
  sort(level,level+n,cmp);
  for(int i=0;i<n;i++){
    if(i!=n-1){
        cout<<level[i].key<<' ';
    }else{
        cout<<level[i].key;
    }
  }
  return 0;
}

当然,也可以选择建树的做法:

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cmath>
#include<queue>
#include<cstring>
#include<vector>
#include<stack>
#include<map>
#define MAX 1000005
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;

int n,cnt=0;//节点个数
int post[35],in[35];

struct node{
    int key;
    node *left;
    node *right;
};

void level_output(node* root){//层序打印
    queue<node *>q;
    q.push(root);//根节点入队
    while(!q.empty()){
        node *top=q.front();
        q.pop();
        printf("%s%d",cnt==0?"":" ",top->key);
        if(!cnt) cnt++;
        if(top->left!=NULL) q.push(top->left);
        if(top->right!=NULL) q.push(top->right);
    }
}

node* build_tree(int r,int start,int ends){
    if(start>ends){
        return NULL;
    }
    int i=start;
    while(i<ends&&post[r]!=in[i]) i++;
    node *root=(node *)malloc(sizeof(node));
    root->key=post[r];
    root->left=build_tree(r-(ends-i+1),start,i-1);
    root->right=build_tree(r-1,i+1,ends);
    return root;
}


int main(){
    cin>>n;
    for(int i=0;i<n;i++){//读入后序序列
        cin>>post[i];
    }
    for(int i=0;i<n;i++){
        cin>>in[i];
    }
    node *root=build_tree(n-1,0,n-1);
    level_output(root);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值