前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >L2-006 树的遍历 (25 分)

L2-006 树的遍历 (25 分)

作者头像
Lokinli
发布2023-03-09 15:45:29
1560
发布2023-03-09 15:45:29
举报
文章被收录于专栏:以终为始以终为始

L2-006 树的遍历 (25 分)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

代码语言:javascript
复制
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:

代码语言:javascript
复制
4 1 6 3 5 7 2
代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 10;
struct node
{
    int data;
    struct node *lc, *rc;
};
int a[maxn],b[maxn];
struct node *creat(int a[], int b[], int n) // A是中序,B是后序
{
    struct node *root;
    if(n <= 0) return NULL; // 最后的
    int i = 0;
    root = (struct node *)malloc(sizeof(struct node ));
    root -> data = b[n - 1]; //后序的最后一个是根节点
    for(i = 0; i < n; i ++)
    {
        if(a[i] == b[n - 1]) break; // 找到中序的这个点,就是左右子树的分界线
    }
    root -> lc = creat(a,b,i); // 左子树
    root -> rc = creat(a + i + 1,b + i,n - i - 1); // 右子树,A中序来说是根节点右边一个开始,中序来说就是右边这些,长度要减去根和右边的
    return  root;
}
void level(struct node *root)
{
    if(root != NULL)
    {
        queue<node*>q;
        q.push(root);
        bool f = 1;
        while(!q.empty())
        {
            struct node *x;
            x = q.front();
            q.pop();
            if(f)printf("%d", x -> data),f = 0;
            else printf(" %d", x->data);
            if(x->lc)q.push(x->lc);
            if(x->rc)q.push(x->rc);
        }
    }
    printf("\n");
}
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i ++) scanf("%d", &a[i]);
    for(int i = 0; i < n; i ++) scanf("%d", &b[i]);
    struct node *root;
    root = creat(b,a,n);
    level(root);
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-03-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 输入格式:
  • 输出格式:
  • 输入样例:
  • 输出样例:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档