pat 團體賽練習題集 L2-006. 樹的遍歷


給定一棵二叉樹的后序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這里假設鍵值都是互不相等的正整數。

輸入格式:

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

輸出格式:

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

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

題目很簡單,就是已知后序中序求層序。其實和已知后序中序求前序一樣的做法,只要將求得的序列用數組保存起來,用數組存起來的序列就是層序遍歷的結果。

//Asimple
#include <bits/stdc++.h>
#define INF 1e10
#define mod 10007
#define swap(a,b,t) t = a, a = b, b = t
#define CLS(a, v) memset(a, v, sizeof(a))
#define debug(a)  cout << #a << " = "  << a <<endl
#define abs(x) x<0?-x:x
using namespace std;
typedef long long ll;
const int maxn = 35;
int n;
int pos[maxn], in[maxn];
vector<int> res(10000, -1);

void solve(int root, int s, int e, int index) {
    if( s > e ) return ;
    int i = s;
    while( i<e && in[i]!=pos[root])i++;
    res[index] = pos[root];
    solve(root-1-e+i, s, i-1, index*2+1);
    solve(root-1, i+1, e, index*2+2);
}

void input() {
    cin >> n;
    for(int i=0; i<n; i++) cin >> pos[i] ;
    for(int i=0; i<n; i++) cin >> in[i];
    solve(n-1, 0, n-1, 0);
    int cnt = 0;
    for(int i=0; i<res.size(); i++) {
        if( res[i]!=-1 && cnt!=n-1 ) {
            printf("%d ", res[i]);
            cnt ++;
        } else if(res[i]!=-1){
            printf("%d\n", res[i]);
            break;
        }
    }
}

int main() {
    input();
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM