zl程序教程

您现在的位置是:首页 >  后端

当前栏目

L2-011 玩转二叉树 (25 分)

二叉树 25 玩转 L2 011
2023-06-13 09:17:22 时间

L2-011 玩转二叉树 (25 分)

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

4 6 1 7 5 3 2

&:一开始自己还重建了两次树,一次是按题意,然后跑了一遍后序,然后把两个序列翻转,然后又建了一次树,最后跑了一遍层次遍历。 &:于是乎,发现题目要的就是层次遍历的时候先遍历右孩子就好了。

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    struct node *lc, *rc;
};
int a[100],b[100];
int n;
struct node *creat(int len, int a[], int b[])
{
    if(len == 0) return NULL;
    int i;
    struct node *root;
    root = new node;
    root -> data = a[0];
    for(i = 0; i < len; i ++)
    {
        if(a[0] == b[i])
        {
            break;
        }
    }
    root -> lc = creat(i, a + 1, b);
    root -> rc = creat(len - i - 1,a + i + 1, b + i + 1);
    return root;
};
void level(struct node *root)
{
    queue<node*>q;
    q.push(root);
    bool f = true;
    while(!q.empty())
    {
        struct node *x = q.front();
        if(f)
        {
            printf("%d", x -> data);
            f = false;
        }
        else printf(" %d",x -> data);
        q.pop();
        if(x -> rc) q.push(x -> rc);
        if(x -> lc) q.push(x -> lc);
    }
    printf("\n");
    return ;
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i = 0; i < n; i ++) scanf("%d", &b[i]);
        for(int i = 0; i < n; i ++) scanf("%d", &a[i]);
        struct node *root;
        root = creat(n,a,b);
        level(root);
    }

    return 0;
}