根据后序和中序遍历输出先序遍历

简介: 树的遍历

本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。

输入格式:
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。

输出格式:
在一行中输出Preorder: 以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。

输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;

const int N=100;

typedef struct edge* node;


struct edge
{
    int data;
    node l;
    node r;
};


node insert(int *a, int *b, int n)
{
    int i;
    int n1=0, n2=0;
    int m1=0, m2=0;
    int la[N], ra[N];
    int lb[N], rb[N];
    node BT=NULL;
    if(n==0)
        return NULL;
    BT=(node) malloc(sizeof(struct edge));
    if(BT==NULL)
        return NULL;
    memset(BT, 0, sizeof(edge));
    BT->data=a[n-1];
    for(i=0;i<n;i++)
    {
        if(i<=n1&&b[i]!=a[n-1])
            lb[n1++]=b[i];
        else if(b[i]!=a[n-1])
            rb[n2++]=b[i];
    }
    for(i=0;i<n-1;i++)
    {
        if(i<n1)
            la[m1++]=a[i];
        else
            ra[m2++]=a[i];
    }
    BT->l=insert(la, lb, n1);
    BT->r=insert(ra, rb, n2);
    return BT;
}


void preorder(node BT)
{
    if(!BT)
        return;
    printf(" %d", BT->data);
    preorder(BT->l);
    preorder(BT->r);
}


int main()
{
    int n;
    int a[N], b[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]);
    node BT;
    BT=insert(a, b, n);
    printf("Preorder:");
    preorder(BT);
    return 0;
}
相关文章
|
6月前
排序二叉树的创建及先序、中序、后序输出二叉树
排序二叉树的创建及先序、中序、后序输出二叉树
27 1
|
6月前
|
存储 算法 C++
【二叉树】利用前序和中序遍历结果生成二叉树并输出其后序和层序遍历结果
【二叉树】利用前序和中序遍历结果生成二叉树并输出其后序和层序遍历结果
64 0
|
存储
刷题之完全二叉树的权值和小字辈及根据后序和中序遍历输出先序遍历
刷题之完全二叉树的权值和小字辈及根据后序和中序遍历输出先序遍历
121 0
|
存储 C++
二叉树的四种遍历方式(前序遍历,中序遍历,后序遍历,层序遍历)C++语言
二叉树的四种遍历方式(前序遍历,中序遍历,后序遍历,层序遍历)C++语言
204 0
|
JavaScript 前端开发 Java
二叉树的先序、中序、后序遍历
二叉树的先序、中序、后序遍历
107 0
二叉树的先序、中序、后序遍历
|
算法 前端开发 程序员
二叉树的后序遍历序列
二叉树的后序遍历序列
二叉树的后序遍历序列
先序、中序、后序遍历确定唯一树
快速学习先序、中序、后序遍历确定唯一树
先序、中序、后序遍历确定唯一树
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历
94 0