L2-011. 玩转二叉树

已知二叉树的中序遍历和前序遍历,求出它反转后的层序遍历

反转的意思就是将这棵树的左子树和右子树调换位置输出,这题给的是中序遍历和前序遍历,其他和L2-006一样。

/* 7 1 2 3 4 5 6 7 4 1 3 2 6 5 7 * 4 6 1 7 5 3 2 */
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node
{
    struct node *left;
    struct node *right;
    int data;
}Node;
Node *binarytree(int a[],int b[],int len)
{
    int i;
    if (len==0)
    return NULL;
    Node *q;
    q=(Node *)malloc(sizeof(Node));
    q->data=a[0];
    for (i=0;i<len;i++)
    {
        if (b[i]==a[0])
        break;
    }
    q->left=binarytree(a+1,b,i);
    q->right=binarytree(a+i+1,b+i+1,len-1-i);
    return q;
}
int main() 
{
    int n,i;
    cin>>n;
    int pre[n],mid[n];
    for (i=0;i<n;i++)
    cin>>mid[i];
    for (i=0;i<n;i++)
    cin>>pre[i];
    Node *que[n];
    int head=0,tail=0;
    que[tail++]=binarytree(pre,mid,n);
    while (head<tail)
    {
        cout<<que[head]->data;
        if (head!=n-1)
        cout<<" ";
        if (que[head]->right!=NULL)
        que[tail++]=que[head]->right;
        if (que[head]->left!=NULL)
        que[tail++]=que[head]->left;
        head++;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:24
大家还是用ai改吧,我心疼得要死,就当花钱买教训吧,人家直接拿完钱就跑路了
程序员小白条:简历修改700....神奇,又不是帮你面试,咋的,简历修改从双非变92了还是没实习变成有大厂实习了
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务