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

1020. Tree Traversals

时间:2015-03-02 13:16:06      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:c++   pat   

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;

typedef struct Node
{
        int id;
        struct Node *left,*right;
        }Node;
Node * Creat(int * post,int ps,int pe,int * in,int is,int ie);
void BFS (Node * root);
int n;

int main ()
{
    int i;
    scanf("%d",&n);
    int *post=new int[n];
    int *in=new int[n];
    for( i=0;i<n;i++)
    {
         scanf("%d",post+i);
         }
    for( i=0;i<n;i++)
    {
         scanf("%d",in+i);
         }
    Node *root=Creat(post,0,n-1,in,0,n-1);
    BFS(root);
    printf("\n");
    system("pause");
    return 0;
    }
void BFS (Node * root)
{
     queue<Node *>q;
     q.push(root);
     Node *temp=new Node;
     int count=0;
     while( !q.empty())
     {
            temp=q.front();
            q.pop();//出队
            printf("%d",temp->id);
            count++;
            if(count<n) printf(" ");
            if(temp->left) q.push(temp->left);
            if(temp->right) q.push(temp->right); 
            }
     }
Node * Creat(int * post,int ps,int pe,int * in,int is,int ie)
{
     if(ps>pe) return NULL;
     Node * root=new Node;
     root->id=post[pe];
     int i;
     for( i=is;i<=ie;i++) if(in[i]==root->id) break;
     int num=i-is;
     root->left=Creat(post,ps,ps+num-1,in,is,i-1);
     root->right=Creat(post,ps+num,pe-1,in,i+1,ie);
     return root;
     }

1020. Tree Traversals

标签:c++   pat   

原文地址:http://blog.csdn.net/lchinam/article/details/44016465

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