1. 程式人生 > >【PAT】1064. Complete Binary Search Tree (30)【完全二叉搜尋樹】

【PAT】1064. Complete Binary Search Tree (30)【完全二叉搜尋樹】

題目描述

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

翻譯:一個二叉搜尋樹(BST)按照以下規則遞迴的定義的一棵二叉樹:
1.左子樹僅僅包括鍵值小於該點鍵值的點。
2.右子樹僅僅包括鍵值大於等於該點鍵值的點。
3.左子樹和右子樹均為二叉搜尋樹樹。
一個完全二叉樹(CBT)是一棵完全充滿的數,只有最底層可能有空缺,並且由左向右插入。
現在給你一個由唯一的非負整數鍵值組成的數列,我們需要構建一個特殊的BST,即它同時還是一棵完全二叉樹。你需要輸出BST的按照層級遍歷的數列。

INPUT FORMAT

Each input file contains one test case. For each case, the first line contains a positive integer N (<=1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

翻譯:每個輸入檔案包含一組測試資料。對於每組輸入資料,第一行包括一個正整數N(<=1000)。接著在下一行給出N個唯一的非負整數鍵值。一行內所有數字之間用空格隔開,並且不超過2000。

OUTPUT FORMAT

For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

翻譯:對於每組輸入資料,輸出一行按照水平順序輸出完全二叉搜尋樹的數列。一行內所有數字直接用空格隔開,並且行末尾不能有多餘空格。

Sample Input:

10
1 2 3 4 5 6 7 8 9 0

Sample Output:

6 3 8 1 5 7 9 0 2 4

解題思路

這道題並不需要建立樹,只需要計算出每棵樹的根節點位置即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<queue>
#include<algorithm>
#define INF 99999999
using namespace std;
int N;
int d[1010];
int fun(int a){
    int temp=2;
    while(a>temp-1){
        temp*=2;
    }
    if(a-temp/2+1<temp/4)return a-temp/4+1;
    else return temp/2;
}
typedef pair<int,int> P;
queue<P> q;
void bfs(){
    int flag=0;
    while(!q.empty()){
        P temp=q.front();q.pop();
        int t=fun(temp.second-temp.first+1)+temp.first-1;
        if(flag==0)printf("%d",d[t]),flag=1;
        else printf(" %d",d[t]);
        if(t>temp.first)q.push(P(temp.first,t-1));
        if(t<temp.second)q.push(P(t+1,temp.second));
    }
}
int main(){
    scanf("%d",&N);
    for(int i=0;i<N;i++)
    scanf("%d",&d[i]);
    sort(d,d+N);
    q.push(P(0,N-1));
    bfs();
    printf("\n");
    return 0;
}