二叉树后序遍历和层次遍历

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

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

示例输入

2
abdegcf
dbgeafc
xnliu
lnixu

示例输出

dgebfca
abcdefg
linux
xnuli

提示

 
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>

using namespace std;

char head[200],mid[200];
struct Tree
{
    char c;
    Tree *L;
    Tree *R;
};
Tree *Creat()
{
    Tree *p;
    p=new Tree;
    p->L=NULL;
    p->R=NULL;
    return p;
}
Tree* Build(int low,int high,int begin,Tree* root)
{
    if(low>high)
    {
        return NULL;
    }
    int i;
    for(i=low; i<=high; i++)
    {
        if(head[begin] == mid[i])
        {
            break;
        }
    }
    root=Creat();
    root ->c=mid[i];                                                             //
    root->L=Build(low,i-1,begin+1,root->L);                   //bdeg  cf(前序)
    root ->R=Build(i+1,high,begin+1+i-low,root->R);    //dbge  fc(中序)
    return root;
}
void Output(Tree* root)
{
    if(!root)
        return ;
    Output(root->L);
    Output(root->R);
    printf("%c",root->c);
}
void BFS(Tree* root)
{
    queue<Tree * >Q;
    Tree*p;
    Q.push(root);   //入队
    while(!Q.empty())
    {
        p=Q.front();  //队首
        Q.pop();         //出队
 
        if(!p) return ;   //防止遇到空根 ,  如  以前的题数据为//,,   不加会提示段错误
 //但是此题可以不用加<span id="transmark"></span>

       printf("%c",p->c);
        if(p->L)
        {
            Q.push(p->L);
        }
        if(p->R)
        {
            Q.push(p->R);
        }
    }
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        Tree* Root;
        cin>>head>>mid;
        int len=strlen (mid);
        Root=Build(0,len-1,0,Root);
        Output(Root);
        cout<<endl;
        BFS(Root);
        cout<<endl;
    }
    return 0;
}


你可能感兴趣的:(二叉树后序遍历和层次遍历)