1. 程式人生 > >SDUTOJ2824求二叉樹的層次遍歷

SDUTOJ2824求二叉樹的層次遍歷

求二叉樹的層次遍歷

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

已知一顆二叉樹的前序遍歷和中序遍歷,求二叉樹的層次遍歷。

Input

輸入資料有多組,輸入T,代表有T組測試資料。每組資料有兩個長度小於50的字串,第一個字串為前序遍歷,第二個為中序遍歷。

Output

每組輸出這顆二叉樹的層次遍歷。

Sample Inpu

2
abc
bac
abdec
dbeac

Sample Output

abc
abcde

Hint

Source

fmh

AC程式碼:

#include <bits/stdc++.h>
using namespace std;
struct tree
{
    char c;
    tree *l, *r;
};
char s1[100], s2[100]; // s1前序 s2中序
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--)
    {
        tree *tree;
        cin >> s1 >> s2;
        int len = strlen(s1);
        tree = make(len, s1, s2);
        show(tree);
        cout << endl;
    }
    return 0;
}