码迷,mamicode.com
首页 > 其他好文 > 详细

前序和中序+后序和中序

时间:2017-04-14 22:59:34      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:using   space   namespace   str   for   start   int   tac   algo   

/**由前序遍历和中序遍历得到层次遍历序列**/
#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("\n");
    }
    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("\n");
    }
    return 0;
}
/*
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
*/

 

前序和中序+后序和中序

标签:using   space   namespace   str   for   start   int   tac   algo   

原文地址:http://www.cnblogs.com/w-y-1/p/6710851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!