PAT 1099 Build A Binary Search Tree (30) BST

傳送門

題意:

    讓你建一顆BST樹並輸出其層次遍歷序列.

思路:

    很簡單的一個題目,首先要知道BST的中序遍歷就一定是有序遞增的序列.那麼我們根據這個特性將給定的序列排序,然後按照根據所給的節點信息按照中序遍歷的順序來建樹,最後在輸出層次遍歷序列即可.

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1e2+5;
struct node
{
    int l,r;
}a[maxn];
int n,ans[maxn];
int ord[maxn],cur,tmp[maxn];

void build(int pos)
{
    if(pos == -1)
        return ;
    build(a[pos].l);
    tmp[pos] = ans[cur++];
    build(a[pos].r);
    return ;
}
void bfs(int root)
{
    queue<int>Q;
    while(!Q.empty()) Q.pop();
    Q.push(root);
    int num = 0;
    while(!Q.empty())
    {
        int p = Q.front();
        Q.pop();
        ord[num++] = tmp[p];
        if(a[p].l != -1)
            Q.push(a[p].l);
        if(a[p].r != -1)
            Q.push(a[p].r);
    }
    return ;
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i = 0;i < n;++i)
            scanf("%d %d",&a[i].l,&a[i].r);
        for(int i = 0;i < n;++i)
            scanf("%d",&ans[i]);
        sort(ans,ans + n);
        cur = 0;
        build(0);
        bfs(0);
        for(int i = 0;i < n;++i)
            printf("%d%c",ord[i],i == n - 1?'\n':' ');
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章