求二叉树的先序遍历(中序+后序==先序)

Problem Description

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

Input

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

Output

 输出二叉树的先序遍历序列

Sample Input

2
dbgeafc
dgebfca
lnixu
linux

Sample Output

abdegcf
xnliu

Hint

#include<bits/stdc++.h>
using namespace std;
struct node
{
    node *l,*r;
    char data;
};
node *create(char *middle,char *finall,int len)
{
    if(len<=0)
        return NULL; //空节点
    node *root;
    root=new node;
    root->data=finall[len-1];//后序遍历左右根的最后一个肯定是根节点,依次迭代即可
    int i;
    for(i=0;i<len;i++) //找到左右子树分界点
    {
        if(middle[i]==finall[len-1])
            break;
    }
    root->l=create(middle,finall,i);//左子树为i分界点的左边
    root->r=create(middle+i+1,finall+i,len-1-i);//右子树为i分界点的右边,不过将中序向后挪1位,目的是跳过根节点
    return root;
}
void previousshow(node *root)
{
    if(root)
    {
        cout<<root->data;
        previousshow(root->l);
        previousshow(root->r);
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        node *root;
        char middle[100],finall[100];
        cin>>middle>>finall;
        int len=strlen(middle);  //都一样
        root=create(middle,finall,len);//建立出二叉树,然后再先序遍历即可
        previousshow(root);
        cout<<endl;
    }
    return 0;
}


/***************************************************
User name: ACM18171信科1801张林
Result: Accepted
Take time: 0ms
Take Memory: 188KB
Submit time: 2019-02-24 22:36:36
****************************************************/

Source

GYX

题解:根据中序和后序条件建立起二叉树,先序遍历即可。

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/87909165