7-1 玩转二叉树

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

输入格式:

输入第一行给出一个正整数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

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

栈限制

8192 KB

复制代码
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;//给int取别名
typedef struct Tree* BinTree;//给节点取别名
struct Tree
{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};
int qian[100],zhong[100];
BinTree Creat(int q,int z,int n)
{
    BinTree T;
    int i;
    if(n<=0)
    {
        return T=NULL;
    }
    else
    {
        T=(BinTree)malloc(sizeof(struct Tree));
        T->Data=qian[q];
        for(i=0;qian[q]!=zhong[z+i];i++);
        T->Left=Creat(q+1,z,i);
        T->Right=Creat(q+i+1,z+i+1,n-i-1);
    }
    return T;//返回树根节点
}
void LevelorderTraversal(BinTree T)
{
    BinTree Q,a[1000];
    int front=0,tail=0;
    static int c=0;
    if(T)
    {
        a[++tail]=T;
    }
    while(front!=tail)
    {
        Q=a[++front];
        if(c==0)
        {
            printf("%d",Q->Data);
            c++;
        }
        else
        {
            printf(" %d",Q->Data);
        }
        if(Q->Right)
        {
            a[++tail]=Q->Right;
        }
        if(Q->Left)
        {
            a[++tail]=Q->Left;
        }
    }
}
int main()
{
    int N;
    BinTree T;
    scanf("%d",&N);//输入一个正整数
    for(int i=0;i<N;i++)
    {
        scanf("%d",&zhong[i]);
    }
    for(int i=0;i<N;i++)
    {
        scanf("%d",&qian[i]);
    }
    T=Creat(0,0,N);
    LevelorderTraversal(T);
    return 0;
}
相关推荐
wengqidaifeng几秒前
数据结构(三)栈和队列(下)队列:程序世界的秩序之美
数据结构
努力学算法的蒟蒻1 分钟前
day84(2.12)——leetcode面试经典150
算法·leetcode·面试
程序员酥皮蛋4 分钟前
hot 100 第二十三题 23.反转链表
数据结构·算法·leetcode·链表
TracyCoder12320 分钟前
LeetCode Hot100(51/100)——155. 最小栈
数据结构·算法·leetcode
wu_asia24 分钟前
每日一练叁
算法
dalong1026 分钟前
A24:圈住小猫游戏
笔记·算法·游戏·aardio
Y.O.U..30 分钟前
力扣刷题-86.分隔链表
算法·leetcode·链表
学编程的闹钟31 分钟前
C语言GetLastError函数
c语言·开发语言·学习
智算菩萨43 分钟前
上下文学习的贝叶斯推断视角:隐式梯度下降还是隐式贝叶斯?
人工智能·算法
TracyCoder1231 小时前
LeetCode Hot100(52/100)——394. 字符串解码
算法·leetcode·职场和发展