二叉树遍历

来源:互联网 发布:unity3d安装步骤 编辑:程序博客网 时间:2024/06/06 05:54

二叉树遍历习题

题意:

给出一个二叉树的后序遍历序列和中序遍历序列,求这颗二叉树的层序遍历序列。

输入

72 3 1 5 7 6 41 2 3 4 5 6 7

输出

4 1 6 3 5 7 2
#include <iostream>#include <cstring>#include <queue>#include <algorithm>using namespace std;const int maxn=50;typedef struct node{    int data;    node* lchild;    node* rchild;}Node;int pre[maxn],in[maxn],post[maxn];  //先序,中序,后序 int n;      //结点个数 //create 函数返回构建出的二叉树的根结点地址Node* create( int postL,int postR,int inL,int  inR ) {    if(postL > postR)    {        return NULL;    //后序序列长度小于等于0时,直接返回     }    Node* root = new Node;    root->data = post[postR];   //新结点的数据域为根结点的值     int k;    for(k=inL;k<=inR;k++)    {        if(in[k] == post[postR] )   //根据先序序列中根结点的值,在中序序列中找出根结点的位置         {            break;        }    }    int num_left=k-inL;     //左子树的结点个数    //分治递归创建左子树和右子树    root->lchild = create(postL,postL+num_left-1,inL,k-1);    root->rchild = create(postL+num_left,postR-1,k+1,inR);    return root; }//已经输出的结点的个数 int num=0;void BFS(Node* root){    queue<Node*> queue;    queue.push(root);    while(!queue.empty())    {        Node* now=queue.front();        queue.pop();        printf("%d",now->data);        num++;        if(num<n)        {            printf(" ");        }        if(now->lchild!=NULL)        {            queue.push(now->lchild);        }        if(now->rchild!=NULL)        {            queue.push(now->rchild);        }    }}int main(){    scanf("%d",&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= create(0,n-1,0,n-1);    BFS(root);    return 0;}