求二叉树的层次遍历(前序+中序==层次)

Problem Description

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

Input

输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。

Output

每组输出这颗二叉树的层次遍历。

Sample Input

2
abc
bac
abdec
dbeac

Sample Output

abc
abcde

Hint

Source

fmh

#include<bits/stdc++.h>
using namespace std;
struct node
{
    node *l,*r;
    char data;
};
node *create(char *previous,char *middle,int len)
{
    if(len<=0)
        return NULL;  //空节点
    node *root;
    root=new node;
    root->data=previous[0];  //先序遍历,第一个肯定是根节点,如此迭代
    int i;
    for(i=0;i<len;i++)
    {
        if(middle[i]==previous[0]) //找到中序的该根节点,并依次迭代
            break;
    }
    root->l=create(previous+1,middle,i); //左子树中先序遍历字串向后挪一位,中序不变,但i控制了长度
    root->r=create(previous+i+1,middle+i+1,len-i-1);//右子树中先序遍历和中序遍历都向后挪i+1位,长度变成总长度减去前半部分的长度(注意+1)
    return root;
}
void layershow(node *root)
{
    queue<node*>que;//注意这里是node*,坑死我了
    if(root)        //一定要特判,不然会RE
    {
        que.push(root);
        cout<<que.front()->data;
    }
    while(que.size())
    {
        node *root=que.front(); //常用手段
        que.pop();
        if(root->l)  //依次找左右儿子输出即可
        {
            cout<<root->l->data;
            que.push(root->l);
        }
        if(root->r)
        {
            cout<<root->r->data;
            que.push(root->r);
        }
    }
}
int main()
{
    int t;
    cin>>t;
    char previous[100],middle[100];
    while(t--)
    {
        cin>>previous>>middle;
        node *root;
        int len=strlen(previous);
        root=create(previous,middle,len);
        layershow(root);
        cout<<endl;
    }
    return 0;
}


/***************************************************
User name: ACM18171信科1801张林
Result: Accepted
Take time: 0ms
Take Memory: 196KB
Submit time: 2019-02-24 23:01:59
****************************************************/

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/87909504
今日推荐