L2-006 树的遍历(各种遍历的相互转换)

PTA | 程序设计类实验辅助教学平台

#include<bits/stdc++.h>

using namespace std;

const int N = 31;
int n;
int in[N],post[N],h[N];

struct node{
    int data;
    node *lchild = NULL,*rchild = NULL;
};

node* build(int la,int ra,int lb,int rb)
{
    if(la>ra||lb>rb) return NULL;
    node *ne = new node;
    ne -> data = post[ra];
    int cnt = rb - h[post[ra]];
    ne -> lchild = build(la,ra - cnt - 1,lb,h[post[ra]] - 1);
    ne -> rchild = build(ra-cnt,ra-1,h[post[ra]] + 1,rb);
    return ne;
}

void level(node *v)
{
    queue<node*> q;
    q.push(v);
    int cnt = 1;
    while(q.size()){
    	auto i = q.front();
    	q.pop();
    	if(cnt == 1) cout<<i -> data;
    	else cout<<' '<<i->data;
    	if(i -> lchild)q.push(i -> lchild);
    	if(i -> rchild)q.push(i -> rchild);
    	cnt++;
	}
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++) cin>>post[i];
    for(int i=0;i<n;i++) cin>>in[i],h[in[i]] = i;
    node *root = new node;
    root = build(0,n-1,0,n-1);
    level(root);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值