中序后序遍历转先序遍历

#include<iostream>
using namespace std;
#define N 100
void FunX(int L, int R);
int FunEnd(int L, int R);
int H[N], Z[N], X[N];
int n,k=1;
int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> H[i];
    for (int i = 1; i <= n; i++)
        cin >> Z[i];
    cout << "Preorder: ";
    FunX(1,n);
    for (int i = 1; i <= n; i++)
    {
        if (i == 1)
            cout << X[i];
        else
            cout << ' ' << X[i];
    }
    cout << endl;
    system("pause");
    return 0;
}
void FunX(int L, int R)
{
    if (L > R)
        return;
    int P = FunEnd(L, R);
    X[k++] = Z[P];
    FunX(L, P - 1);
    FunX(P + 1, R);
}
int FunEnd(int L, int R)
{
    int Pos,PosEnd=0,P=0;
    for (int i = L; i <= R; i++)
    {
        for (int j = 1; j <= ::n; j++)
        {
            if (Z[i] == H[j])
            {
                Pos = j;
                break;
            }
        }
        if (Pos > PosEnd)
        {
            PosEnd = Pos;
            P = i;
        }
    }
    return P;
}

猜你喜欢

转载自blog.csdn.net/zero_1778393206/article/details/80543645