1020 Tree Traversals(25 分)【树的遍历】

6 篇文章 0 订阅
4 篇文章 0 订阅

题意:已知后序遍历和中序遍历,构造树,然后输出层序遍历(用bfs)

#include <bits/stdc++.h>
using namespace std;
const int maxn=35;
int n;
int post[maxn];
int in[maxn];

typedef struct node{
    int val;
    struct node *lchild;
    struct node *rchild;
}node;

node *buildTree(int pl,int pr,int il,int ir)
{
    if(pl>pr)
        return NULL;
    //因为后序遍历的最后一个结点一定为根,先找到根,然后根据中序遍历划分出左右子树,在循环此查找
    int t=0;
    while(in[t]!=post[pr])  
        t++;
    node *binode = (node*)malloc(sizeof(node));
    binode->val = post[pr];
    binode->lchild = buildTree(pl,pl+t-il-1,il,t-1);
    binode->rchild = buildTree(pl+t-il,pr-1,t+1,ir);
    return binode;
}

void bfs(node *root)
{
    queue<node *>q;  //队列元素用结构体指针
    node *temp=NULL;
    q.push(root);
    int f=0;
    while(!q.empty()){
        temp=q.front();
        q.pop();
        if(temp){
            if(!f){
                cout<<temp->val;
                f=1;
            }
            else{
                cout<<" "<<temp->val;
            }
            q.push(temp->lchild);
            q.push(temp->rchild);
        }

    }
    cout<<endl;
}

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;
    root=buildTree(0,n-1,0,n-1);
    bfs(root);

    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值