前序和中序+后序和中序

/**由前序遍历和中序遍历得到层次遍历序列**/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
#include<algorithm>

using namespace std;
const int maxn=107;

int T[maxn], n;
int preorder[maxn], inorder[maxn];

void BuildTree(int root, int start, int ends, int index)
{
    int mid=start;
    if(start>ends || root>n)return;

    T[index]=preorder[root];

    while(inorder[mid]!=preorder[root] && mid<ends)
        mid++;
    BuildTree(root+1, start, mid-1, index*2);
    BuildTree(root+1+mid-start, mid+1, ends, index*2+1);
}
int main()
{
    while(~scanf("%d", &n))
    {
        for(int i=1; i<=n; i++)
            scanf("%d", &preorder[i]);
        for(int i=1; i<=n; i++)
            scanf("%d", &inorder[i]);
        BuildTree(1, 1, n, 1);

        for(int i=1; i<=2*n+1; i++)
        {
            if(T[i]!=0)
                printf("%d ", T[i]);
        }
        printf("
");
    }
    return 0;
}
/*
7
4 1 3 2 6 5 7
1 2 3 4 5 6 7
*/

/**由后序遍历和中序遍历得到层次遍历序列**/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
#include<algorithm>

using namespace std;
const int maxn=107;

int T[maxn], n;
int posorder[maxn], inorder[maxn];

void  BuildTree(int root, int start, int ends, int index)
{
    if(start>ends || root>n)return;
    int mid=start;
    T[index]=posorder[root];

    while(inorder[mid]!=posorder[root] && mid<ends)
        mid++;
    BuildTree(root-1-ends+mid, start, mid-1, index*2);
    BuildTree(root-1, mid+1, ends, index*2+1);
}

int main()
{
    while(~scanf("%d", &n))
    {
        for(int i=1; i<=n; i++)
            scanf("%d", &posorder[i]);
        for(int i=1; i<=n; i++)
            scanf("%d", &inorder[i]);

        BuildTree(n, 1, n, 1);

        for(int i=1; i<=2*n+1; i++)
        {
            if(T[i]!=0)
                printf("%d ", T[i]);
        }
        printf("
");
    }
    return 0;
}
/*
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
*/
原文地址:https://www.cnblogs.com/w-y-1/p/6710851.html