已知中序和前序构建一棵树并用层序输出

题目:输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
注意:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:

7
1 2 3 4 5 6 7
4 1 3 2 6 5 7

输出样例:

4 1 6 3 5 7 2

代码实现:

#include<iostream>
#include<stdio.h>
using namespace std;

struct node
{
    int data;
    node *left,*right;
};

node *creat(int *pre,int *in,int n)//定义构建树的函数,传入的参数分别为前序遍历数组,后续遍历数组,结点数
{
    node *root=new node;
    if(n<=0)
    {
        return NULL;
    }
    root->data=pre[0];//将前序遍历根的data值赋值
    int q;//记录中序遍历中根结点的位置
    for(q=0;q<n;q++)
    {
        if(pre[0]==in[q])
        {
            break;
        }
    }
    root->left=creat(pre+1, in, q);//递归实现对left的构建
    root->right=creat(pre+q+1, in+q+1, n-q-1);//递归实现对right的构建
    return root;
}

int flag=1;
void cengxubianli(node *root)
{
    int in=0,out=0;
    node *a[10000];
    a[in++]=root;//根结点入队
    while(in>out)//in<=out表示队列为空
    {
        if(a[out]!=NULL)
        {
            if(flag)
            {
                printf("%d",a[out]->data);
                flag=0;
            }
            else
            {
                printf(" %d",a[out]->data);
            }
            a[in++]=a[out]->left;//根结点的左孩子入队
            a[in++]=a[out]->right;
        }
        out++;
    }
}

int main()
{
    int n;
    cin>>n;
    int a[n],b[n];
    node *root;
    root=new node;
    for(int i(0);i<n;i++)
    {
        cin>>b[i];
    }
    for(int i(0);i<n;i++)
    {
        cin>>a[i];
    }
    root=creat(a, b, n);
    cengxubianli(root);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值