7-1 根據后序和中序遍歷輸出先序遍歷 (25 分)


7-1 根據后序和中序遍歷輸出先序遍歷 (25 分)

本題要求根據給定的一棵二叉樹的后序遍歷和中序遍歷結果,輸出該樹的先序遍歷結果。

輸入格式:

第一行給出正整數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

  

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct BiNode
{
    int data;
    struct BiNode *lchild;
    struct BiNode *rchild;
}BiNode, *BiTree;
BiTree BuildPreTree(int *End, int *Mid, int n)//根據后序和中序構造二叉樹
{
    if(n <= 0)
        return NULL;
    int *p = Mid;
    while(*p != *(End+n-1))//后序的最后一個數是根節點,將p移動到中序的根節點位置,p就將中序分成左子樹部分和右子樹部分
          p++;
    BiTree T;
    T = (BiNode*)malloc(sizeof(BiNode));
    T->data = *p;
    int len_l = p - Mid;
    T->lchild = BuildPreTree(End, Mid, len_l);//找到左子樹根節點,遞歸
    T->rchild = BuildPreTree(End+len_l, Mid+len_l+1, n-len_l-1);
    return T;
}
void CoutPre(BiTree T)//先序輸出
{
    if( T != NULL ){
        printf(" %d", T->data);
        CoutPre(T->lchild);
        CoutPre(T->rchild);
    }

}
int main()
{
    int N, *End, *Mid;
    scanf("%d", &N);
    End = (int*)malloc(sizeof(int)*N);
    Mid = (int*)malloc(sizeof(int)*N);
    for(int i=0; i<N; i++)
        scanf("%d", &End[i]);
    for(int i=0; i<N; i++)
        scanf("%d", &Mid[i]);
    BiTree T = BuildPreTree(End, Mid, N);
    printf("Preorder:");
    CoutPre(T);
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM