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

版权声明:iQXQZX https://blog.csdn.net/Cherishlife_/article/details/84986638

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

https://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2711/pid/2137

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

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

Sample Input

2
abdegcf
dbgeafc
xnliu
lnixu

Sample Output

dgebfca
abcdefg
linux
xnuli

Hint

Source

ma6174

#include <bits/stdc++.h>
using namespace std;
struct tree
{
    char c;
    tree *l, *r;
};
int cnt;
char s1[100], s2[100], ans[100];                       // s1先序 s2中序 ans为后序
void tree_back(int len, char *s1, char *s2, char *ans) /* 由先序和中序推出二叉树的后序*/
{
    int i;
    if (len <= 0)
        return;
    for (i = 0; i < len; i++)
    {
        if (s2[i] == s1[0])
            break;
    }
    tree_back(i, s1 + 1, s2, ans);
    tree_back(len - i - 1, s1 + i + 1, s2 + i + 1, ans + i);
    ans[len - 1] = s1[0];
}
tree *make(int len, char *s1, char *s2) /* 根据前序 中序建立二叉树*/
{
    int i;
    tree *root;
    if (len <= 0) // 递归边界 如果len为0则不能建树
        return NULL;
    root = new tree; // new一个新节点
    root->c = s1[0];
    for (i = 0; i < len; i++)
    {
        if (s2[i] == s1[0]) // 在中序中寻找根节点
            break;
    }
    root->l = make(i, s1 + 1, s2);                       // 递归建立左子树
    root->r = make(len - i - 1, s1 + i + 1, s2 + i + 1); // 递归建立右子树
    return root;
}
void show(tree *root) /* 层序遍历二叉树 // 通过队列实现*/
{
    queue<tree *> q;
    if (root) // 数存在入队
        q.push(root);
    while (!q.empty())
    {
        root = q.front();
        q.pop();
        if (root)
        {
            cout << root->c;
            q.push(root->l);
            q.push(root->r);
        }
    }
}
int main()
{
    int n;
    cin >> n;
    while (n--)
    {
        cnt = 0;
        tree *tree;
        cin >> s1 >> s2; // 输入先序和中序
        int len = strlen(s1);
        tree_back(len, s1, s2, ans); // 找出后序
        ans[len] = '\0';
        cout << ans << endl;      // 输出后序
        tree = make(len, s1, s2); // 还原二叉树
        show(tree);               // 层序遍历二叉树
        cout << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cherishlife_/article/details/84986638
今日推荐