PAT L2-006. 树的遍历

本文介绍了一种算法,该算法接收二叉树的后序遍历和中序遍历序列作为输入,并输出对应的层序遍历序列。通过递归构建二叉树,再利用队列实现层序遍历。

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

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。


输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
int mid[100],post[100],pre[100];
int s,n;
struct node{
    int c;
    node *lc,*rc;
};
node *solo(int k,int *mid,int *post)
{
    int i,j;
	if(k<=0)
		return 0;
    node *p;
    p = new node;
    p->lc = p-> rc = NULL;
    p->c = post[k-1];
    for(i = 0;i < n;++ i)
        if(mid[i] == post[k-1])
            break;
    for(j = 0;j < n;++ j)
        if(*mid==mid[j]) break;
	int l=i-j;
	p->lc = solo(l,mid,post);
	p->rc = solo(k-l-1,mid+l+1,post+l);
	return p;
}
void layer(node *head){
    queue<node *>Q;
    while(!Q.empty())
        Q.pop();

    Q.push(head);
    while(!Q.empty()){
        node *u;
        u = Q.front();Q.pop();
        pre[s++] = u->c;
        if(u->lc)
        Q.push(u->lc);
        if(u->rc)
        Q.push(u->rc);
    }
}
int main()
{
	int k,i;

	while(~scanf("%d",&n)){
	    for(i = 0;i < n;++ i){
            scanf("%d",&post[i]);
	    }

	    for(i = 0;i < n;++ i){
            scanf("%d",&mid[i]);
	    }
		s=0;
		node *head = new node;
		head->lc = head->rc = NULL;
		head = solo(n,mid,post);
		layer(head);
		for(i = 0 ;i < s;++ i){
            printf(i==s-1?"%d\n":"%d ",pre[i]);
		}
	}
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值