1. 程式人生 > 其它 >PAT甲級 1099 Build A Binary Search Tree (30 分)

PAT甲級 1099 Build A Binary Search Tree (30 分)

題目大意:

給出了一顆含有N個結點的樹的結構,即每個結點的左子樹編號和右子樹編號,現在有N個數要放到這顆樹的結點上,使之滿足二叉搜尋樹的性質。

思路:

二叉搜尋樹的性質:

  • 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
  • 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
  • 它的左、右子樹也分別為二叉排序樹

根據性質和中序遍歷的特點,即該樹中序遍歷(左根右)的結點的值一定是從小到大排序,只需將輸入的結點值排序。然後我們可以根據中序遍歷來重構這顆樹,再利用bfs求得層序遍歷。總體來說是考查中序遍歷和二叉搜尋樹的性質。

程式碼:

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

int n;
struct node{
    int l, r;
    int data;
}a[N << 1];
int w[N];
int ind;
vector<int> ans;

void inorder(int pos){
    if(pos == -1) return;
    inorder(a[pos].l);
    a[pos].data = w[ind++];
    inorder(a[pos].r);
}

void bfs(){
    queue<node> q;
    q.push(a[0]);
    while(q.size()){
        node t = q.front(); q.pop();
        ans.push_back(t.data);
        if(t.l != -1) q.push(a[t.l]);
        if(t.r != -1) q.push(a[t.r]);
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i].l >> a[i].r;
    }
    for(int i = 0; i < n; i++) cin >> w[i];
    sort(w, w + n);
    inorder(0);
    bfs();

    for(int i = 0; i < ans.size(); i++)
        if(i == 0) cout << ans[i];
        else cout << " " << ans[i];
    
    return 0;
}