1. 程式人生 > 其它 >PAT甲級 1102 Invert a Binary Tree (25 分)

PAT甲級 1102 Invert a Binary Tree (25 分)

題目大意:

一顆二叉樹有 \(N\) 個結點,編號從 \(0 \sim N - 1\),先給出每個結點的左右結點編號(如果左右結點不存在用 \(-\) 表示)。現在請你輸出該二叉樹的反轉二叉樹的層序遍歷和中序遍歷。

思路:

這是一道非常典型的資料結構題。因為根節點沒有父親節點, 我們先利用輸入找出根結點。
中序遍歷的順序是:左跟右, 那麼反轉二叉樹對應原樹中的順序就是:右根左,然後利用 \(dfs\) 就能找出這個序列。
同理,一般我們求層序遍歷都是用 \(bfs\), 因為廣搜的性質就是按照半徑來搜,符合層序遍歷的特點。同理,廣搜時反轉二叉樹左右結點對應原二叉樹右左結點。因此先將右結點入隊,然後左結點入隊。

程式碼:

#include <bits/stdc++.h>
using namespace std;
const int N = 15;

int n;
struct node{
    int l,  r;
}a[N];
bool st[N];
vector<int> ind, tra;

void inorder(int root){
    if(root == -1) return;
    if(a[root].r != -1) inorder(a[root].r);
    ind.push_back(root);
    if(a[root].l != -1) inorder(a[root].l);
}

int main(){
    cin >> n;
    for(int i = 0; i <n; i++){
        char l, r;
        cin >> l >> r;
        if(isdigit(l)) a[i].l = l - '0', st[l - '0'] = true;
        else a[i].l = -1;
        if(isdigit(r)) a[i].r = r - '0', st[r - '0'] = true;
        else a[i].r = -1;   
    }
    int root;
    for(int i = 0; i < n; i++){
        if(st[i] == false){
            root = i;
            break;
        }
    }

    inorder(root);
    queue <int> q;
    q.push(root);
    while(q.size()){
        int t = q.front();
        q.pop();
        tra.push_back(t);
        if(a[t].r != -1) q.push(a[t].r);
         if(a[t].l != -1) q.push(a[t].l);
    }

    for(int i = 0; i < n; i++){
        if(i == 0) cout << tra[i];
        else cout << " " << tra[i];
    }
    cout << endl;
    for(int i = 0; i < n; i++){
        if(i == 0) cout << ind[i];
        else cout << " " << ind[i];
    }
    return 0;
}