根據后序和中序遍歷輸出先序遍歷


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

輸入格式:

第一行給出正整數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<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef int TElemType;
typedef int Status;
#define OK 1
#define ERROR 0
typedef struct BiTNode
{
    TElemType data;
    struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
BiTree CreateTreeByPreAndIn(TElemType *pos,TElemType *in,int len)//歸納:找到根(為數組pos的最后一個元素),創建節點,賦給它,
//也就是創建跟節點。然后遞歸創建左子樹,右子樹,注意左子樹和右子樹的范圍。遞歸邊界為:數組長小於等於0
{
    if(len <= 0)
    return NULL;
    BiTNode* T;//分配空間了嗎
    T = new BiTNode;//!!!!!!!!!!!!!!!!
    T -> data = *(pos + len - 1);//后序遍歷的最后一個為根節點;
    int rool = 0;//從1開始算
    for(int i = 1;i <= len;++i)
    {
        rool++;
        if(*(pos + len - 1) == *(in + i - 1))
        break;
        //p++;
    }//找到在中序中rool的位置
    int length = rool-1;//左子樹長度
    T -> lchild = CreateTreeByPreAndIn(pos,in,length);
    T -> rchild = CreateTreeByPreAndIn(pos + length,in + length + 1,len - length - 1);
    return T;
}
Status PreOrderPrint(BiTree T)
{
    if(T == NULL) return OK;
    printf(" %d",T -> data);//前面帶空格
    PreOrderPrint(T -> lchild);
    PreOrderPrint(T -> rchild);
    return OK;
}
int main()
{
    int len;int *pos;int *in;
    cin>>len;
    pos = (int *)malloc(len * sizeof(int));
    in = (int *)malloc(len * sizeof(int));
    for(int i = 1;i <= len;++i)
    cin>>*(pos + i - 1);
    for(int j = 1;j <= len;++j)
    cin>>in[j-1];
    BiTree T;
    T = CreateTreeByPreAndIn(pos,in,len);
    cout<<"Preorder:";
    PreOrderPrint(T);
}





免責聲明!

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



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