算法14——patA1020 根据二叉树的后序和中序遍历求出该二叉树的层序遍历

题目描述:
  假设二叉树中的所有键都是不同的正整数。给定后序和中序遍历序列,你应该输出相应二叉树的层序遍历序列。

输入格式:
  每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N(≤30),即二叉树中的节点总数。第二行给出后序序列,第三行给出中序序列。一行中的所有数字用一个空格隔开。

输出格式:
  对于每个测试用例,在一行中打印相应二叉树的层次顺序遍历序列。一行中的所有数字必须用一个空格隔开,并且行尾不能有多余的空格。

样例输入:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

样例输出:

4 1 6 3 5 7 2

思路:
  根据后序和中序遍历序列构建出二叉树,然后进行层序遍历即可。假设递归过程中某步的后序序列区间为[postL,postR],中序序列区间为[inL,inR],由后序序列的性质可知,后序序列的最后一个元素为根节点。接着就可以在中序序列中找到这个根节点,中序序列中根节点左边区间的为左子树上的节点,右边的为右子树上的节点。假设在中序序列中in[k]为根节点,那么左子树节点的个数为numLeft = k-inL。因此,左子树的后序序列区间为[postL,postL+numLeft-1],左子树的中序遍历区间为[inL,k-1];右子树的后序遍历区间为[postL+numLeft,postR-1],右子树的中序遍历区间为[k+1,inR]

代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 50;

struct node{
    int data;
    node* lchild;
    node* rchild;
};
int pre[maxn],in[maxn],post[maxn];//先序,中序,后序
int n;//节点个数

//当前二叉树的后序序列区间为[postL,postR],中序序列区间为[inL,inR]
//create函数返回构建出的二叉树的根节点的地址
node* create(int postL,int postR,int inL,int inR){
    if(postL > postR)
        return NULL;//后序序列长度小于等于0时,直接返回
    node* root = new node;
    root->data = post[postR];
    int k;
    for(k = inL ; k <= inR ; k++){
        if(in[k]==post[postR]){
            break;//在中序遍历中找到根节点
        }
    }
    int numLeft = k - inL;//左子树节点的个数
    root->lchild = create(postL,post+numLeft-1,inL,k-1);
    root->rchild = create(postL+numLeft,postR-1,k+1,inR);
    return root;
}

int num = 0;//已经输出的节点个数
void BFS(node* root){
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
        node* now = q.front();
        q.pop();
        printf("%d",now->data);
        num++;
        if(num < n)
            printf(" ");
        if(now->lchild!=NULL)
            q.push(now->lchild);
        if(now->rchild!=NULL)
            q.push(now->rchild);
    }
}

int main(){
    scanf("%d",&n);
    for(int i = 0 ; i < n ; i++)
        scanf("%d",&post[i]);
    for(int i = 0 ; i < n ; i++)
        scanf("%d",&in[i]);
    node* root = create(0,n-1,0,n-1);//建树
    BFS(root);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值