PAT L2-011. 玩转二叉树

题目链接:https://www.patest.cn/contests/gplt/L2-011

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <queue>

using namespace std;

#define INF 0x3f3f3f3f
#define N 50

int  preorder[N], inorder[N];
int pre;  //先序数组的指针,按先序遍历的结点次序依次建树,故设置为全局变量
typedef struct node
{
    int data;
    node *lchild;
    node *rchild;
    node()
    {
        lchild=NULL;
        rchild=NULL;
    }
}Node;


void build(Node *t,int inL,int inR)
{
    int i=inL;
    for(;i<inR;i++){
        if(inorder[i]==preorder[pre])
            break;
    }
    if(i>inL){ //t存在左子树
        pre++;
        Node *lc=new Node; 
        lc->data=preorder[pre];
        t->lchild=lc;
        build(lc,inL,i);
    }
    if(i<inR-1){ //t存在右子树
        pre++;
        Node *rc=new Node;
        rc->data=preorder[pre];
        t->rchild=rc;
        build(rc,i+1,inR);
    }
}


void Bfs(Node *t) //层次遍历的变形
{
    queue<Node *> q;
    printf("%d",t->data);
    q.push(t);
    while(!q.empty()){
        Node *cur=q.front();
        q.pop();
        Node *rc=cur->rchild,*lc=cur->lchild;
        if(rc){
            printf(" %d",rc->data);
            q.push(rc);
        }
        if(lc){
            printf(" %d",lc->data);
            q.push(lc);
        }
    }
}

int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&inorder[i]);
    for(int i=0;i<n;i++)
        scanf("%d",&preorder[i]);
    pre=0;
    Node *t=new Node;//new会调用构造函数,而malloc不会
    t->data=preorder[0];
    build(t,0,n);
    Bfs(t);
    printf("\n");
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值