PTA L2-011 玩转二叉树 (25分)

已知二叉树先序和中序序列,重建二叉树,至于层次遍历只需要在重建完之后的二叉树上先入队右子树即。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO                       \
    ios::sync_with_stdio(false); \
    // cin.tie(0);                  \
    // cout.tie(0);
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int maxn = 1e5 + 100;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
struct Node
{
    int num;
    Node *left;
    Node *right;
};
int mid[40], pre[40];
int n;
Node *creat(int mid[], int pre[], int n)
{
    if (n <= 0)
        return NULL;
    int *p = mid;
    while (p)
    {
        if (*p == *pre)
            break;
        p++;
    }
    Node *T = new Node;
    T->num = *p;
    int len = p - mid;
    T->left = creat(mid, pre + 1, len);
    T->right = creat(p + 1, pre + len + 1, n - len - 1);
    return T;
}
void Level(Node *T)
{
    queue<Node *> q;
    q.push(T);
    int flag = 0;
    while (!q.empty())
    {
        Node *a = q.front();
        q.pop();
        if (flag == 0)
        {
            cout << a->num;
            flag = 1;
        }
        else
        {
            cout << " " << a->num;
        }
        if (a->right)
            q.push(a->right);
        if (a->left)
            q.push(a->left);
    }
    return;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> mid[i];
    for (int i = 0; i < n; i++)
        cin >> pre[i];
    Node *T;
    T = creat(mid, pre, n);
    Level(T);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/108760521
今日推荐