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

L2-006. 树的遍历

时间:2018-03-15 21:07:47      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:mem   clu   else   tree   uil   原因   树的遍历   ==   nbsp   

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:

4 1 6 3 5 7 2

  • 比较水的一道题却写了半天。第一次提交最后一个样例点段错误,原因是空间开小了。
#include<stdio.h>
#include<string.h>

int tree[1000*4+10];

void build(int l1,int r1,int l2,int r2,int pos[],int ino[],int root)///建树,基本操作
{
    if(l1>r1)
        return;
    tree[root]=pos[r1];
    for(int i=0; l2+i<=r2; i++)
    {
        if(pos[r1]==ino[l2+i])
        {
            build(l1,l1+i-1,l2,l2+i-1,pos,ino,root*2);
            build(l1+i,r1-1,l2+i+1,r2,pos,ino,root*2+1);
            break;
        }
    }

}

int main()
{
    int n;
    int ino[50],pos[50];
    memset(tree,0,sizeof(tree));
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        scanf("%d",&pos[i]);
    for(int i=1; i<=n; i++)
        scanf("%d",&ino[i]);
    build(1,n,1,n,pos,ino,1);
    int cnt=0;

    for(int i=1;;i++)////层次遍历
    {
        if(tree[i]!=0)
        {
            cnt++;
            if(cnt==1)
                printf("%d",tree[i]);
            else
                printf(" %d",tree[i]);
            if(cnt==n)
                break;
        }
    }
    return 0;
}

 

 

L2-006. 树的遍历

标签:mem   clu   else   tree   uil   原因   树的遍历   ==   nbsp   

原文地址:https://www.cnblogs.com/zhangzehua/p/8575981.html

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