1. 程式人生 > >團體程式設計天梯賽-練習集L2-011 玩轉二叉樹(構造二叉樹+BFS)

團體程式設計天梯賽-練習集L2-011 玩轉二叉樹(構造二叉樹+BFS)

給定一棵二叉樹的中序遍歷和前序遍歷,請你先將樹做個鏡面反轉,再輸出反轉後的層序遍歷的序列。所謂鏡面反轉,是指將所有非葉結點的左右孩子對換。這裡假設鍵值都是互不相等的正整數。

輸入格式:

輸入第一行給出一個正整數N(<=30),是二叉樹中結點的個數。第二行給出其中序遍歷序列。第三行給出其前序遍歷序列。數字間以空格分隔。

輸出格式:

在一行中輸出該樹反轉後的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多餘空格。

輸入樣例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
輸出樣例:
4 6 1 7 5 3 2

大體題意:
給你二叉樹的中序遍歷和前序遍歷,然後再將所有非葉結點左右孩子對換,最後層序遍歷輸出。
思路:
分析下樣例,思路很明確,先根據中序遍歷和前序遍歷用連結串列的方式構造出二叉樹,然後再層序遍歷輸出即可,只不過這裡的層序遍歷是先右後左的方式。
構造二叉樹用結構體遞迴做,層序遍歷直接bfs即可!
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int *pre,*in,n;
int *ans;
int cnt;
struct Node{
    int v;
    Node* left,*right;
}*root;
queue<Node*>q;
int cnt2 = 0;
Node *build(int *pre,int *in,int len){
    if (len == 0)return NULL;
    Node * node = new Node;
    node->v = *pre;
    ++cnt2;
    if (cnt2==1)root = node;
    int rootdex = 0;
    for (; rootdex < n; ++rootdex)if (in[rootdex] == *pre)break;
    node->left = build(pre+1,in,rootdex);
    node->right = build(pre+1+rootdex,in+rootdex+1,len-rootdex-1);
    return node;
}
void print(){
    while(!q.empty())q.pop();
    q.push(root);
    while(!q.empty()){
        Node *u = q.front();q.pop();
        ans[cnt++] = u->v;
        if (u->right != NULL)q.push(u->right);
        if (u->left != NULL)q.push(u->left);

    }
    for (int i = 0; i < cnt; ++i){
        if (i)printf(" ");
        printf("%d",ans[i]);
    }
}
int main(){
    scanf("%d",&n);
    pre = new int[n];
    in = new int[n];
    ans = new int[n];
    cnt = 0;
    for (int i = 0; i < n; ++i)scanf("%d",&in[i]);
    for (int i = 0; i < n; ++i)scanf("%d",&pre[i]);
    build(pre,in,n);
    print();
    return 0;
}