|后序中序层次|7-10 树的遍历 (25分)

注意new node 必须写 申请地址空间

Node * root = new Node();//可以
struct Node* root;//不行
//给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。
//这里假设键值都是互不相等的正整数。
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
vector<int> v;
int post[50],in[50];
struct Node{
    int data;
    Node* lchild;
    Node* rchild;
};

Node* createTree(int postL,int postR,int inL,int inR){//后序 中序
    if(postL>postR)return NULL;
    int index;
    //struct Node node;
    Node* root = new Node;
    root->data=post[postR];
    for(int i=inL;i<=inR;i++){
        if(in[i]==post[postR]){
            index=i;
            break;
        }
    }
    int leftNum=index-inL;//3
    //2 3 1 5 7 6 |4(root)|
    //1 2 3 |4(root)| 5 6 7-----------------------------
    //2 3 1|| 5 7 6 |4(root)|----------------------------
    //1(root) 2 3 |4(root)| 5 6(root) 7
    root->lchild=createTree(postL,postL+leftNum-1,inL,index-1);//postL,postL+leftNum-1,inL,index-1
    root->rchild=createTree(postL+leftNum,postR-1,index+1,inR);//postL+leftNum,postR-1,index+1,inR
    return root;
}

void bfs(Node* node){
    queue<Node*> q;
    q.push(node);
    
    while(!q.empty()){
        Node* tmp=q.front();
        q.pop();
        v.push_back(tmp->data);
        if(tmp->lchild!=NULL)q.push(tmp->lchild);
        if(tmp->rchild!=NULL)q.push(tmp->rchild);
    }
    
}


int main()
{
    int n;
    cin>>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=createTree(0,n-1,0,n-1);//后序,中序
    bfs(root);
    for(int i=0;i<v.size();i++){
        if(i==0)
            cout<<v[i];
        else
            cout<<" "<<v[i];
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值