SDUT-数据结构实验之求二叉树后序遍历和层次遍历

来源:互联网 发布:st联盟软件下载 编辑:程序博客网 时间:2024/06/05 01:40

数据结构实验之求二叉树后序遍历和层次遍历

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

 已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。

Input

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

Output

每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。

Example Input

2abdegcfdbgeafcxnliulnixu

Example Output

dgebfcaabcdefglinuxxnuli

Hint


#include <bits/stdc++.h>using namespace std;typedef struct node{    int data;    struct node*left,*right;}tree;int k;char s[111];tree*creat(char*s){    tree*root;    if(s[k]==',')    {        k++;        return NULL;    }    else    {        root=(tree*)malloc(sizeof(tree));        root->data=s[k++];        root->left=creat(s);        root->right=creat(s);    }    return root;}void ans(tree*root){    queue<tree*>t;    if(root!=NULL)    {        t.push(root);    }    while(!t.empty())    {        root=t.front();        if(!root->left&&!root->right)            printf("%c",root->data);        t.pop();        if(root->left)            t.push(root->left);         if(root->right)            t.push(root->right);    }}int main(){    while(scanf("%s",s)!=EOF)    {        k=0;        tree*root=NULL;        root=creat(s);        ans(root);        printf("\n");    }    return 0;}


阅读全文
0 0