数据结构上机测试4.1:二叉树的遍历与应用1

来源:互联网 发布:王家卫我爱你知乎 编辑:程序博客网 时间:2024/06/05 15:38

数据结构上机测试4.1:二叉树的遍历与应用1

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。

Input

第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。

Output

输出该二叉树的后序遍历序列。

Example Input

ABDCEFBDAECF

Example Output

DBEFCA

Hint

Author


#include <bits/stdc++.h>using namespace std;struct Btree{    char data;    struct Btree *lc,*rc;};char pre[10010];//前序序列char mid[10010];//中序序列int ans;struct Btree* creat(int len, char *pre, char *mid)//二叉树的重建{    struct Btree *root;    int i ;    if(len == 0)    {        return NULL;    }    root = new Btree;    root -> data = pre[0];//找到根节点(前序遍历的第一位)    for(i = 0; i < len; i++)//在中序序列中找到根节点的位置    {        if(mid[i] == pre[0])            break;    }    root -> lc = creat(i, pre + 1, mid);//递归遍历(左子树的长度,左子树在pre中开始位置的地址,左子树在mid中开始位置的地址)    root -> rc = creat(len-i-1, pre+i+1, mid+i+1);//(右子树的长度,右子树在pre中开始位置的地址,右子树在mid中开始位置的地址)    return root;};void LRD(struct Btree *root)//后序遍历{    if(root)    {        LRD(root -> lc);        LRD(root -> rc);        cout<<root->data;    }}int main(){    ans = -1;    while(cin>>pre>>mid)    {        int len = strlen(pre);        struct Btree *root;        root = creat(len,pre,mid);        LRD(root);        cout<<endl;    }    return 0;}



阅读全文
0 0
原创粉丝点击