1. 程式人生 > >PAT甲級1022

PAT甲級1022

題目描述:

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.

翻譯:一個二叉搜尋樹遞迴地表示為帶有以下特點的二叉樹

①左子樹的節點的值都小於當前節點的值

②右子樹的節點的值都大於等於當前節點的值

左子樹和右子樹也同時符合二叉搜尋樹的特點

一個完全二叉樹是完全填充的樹,除了最底層,是從左到右填充

現在給定一系列不同的非負整數值,如果需要樹也必須是CBT,則可以構造唯一的BST。您應該輸出這個BST的層序遍歷序列。

 

過程:

①先構造一個二叉樹,利用完全二叉樹的性質

void creatTree(int root)
{
    if(root>N) return ;
    int lchild = root * 2, rchild = root *2 + 1;
    creatTree(lchild);
    tree[root] = node[pos++];   //利用陣列儲存樹的節點
    creatTree(rchild);
}

將輸入的測試的資料進行排序,從小到大,再依次中序放入陣列,最後對陣列進行輸出,即可得到所要的輸出。

完整程式碼段

#include <iostream>
#include<algorithm>
using namespace std;
int tree[1010];
int node[1010];
int pos = 1;
void creatTree(int root, int N)
{
    if (root > N) return ;
    int lchild = root * 2;
    int rchild = root * 2 + 1;
    creatTree(lchild,N);
    tree[root] = node[pos++];
    creatTree(rchild,N);
}

bool cmp(int a, int b){
    return a<b;
}

int main()
{
    int N;
    cin>>N;
    for(int i=1;i<=N;i++)
        cin>>node[i];
    sort(node+1,node+N+1,cmp);
    
    creatTree(1,N);
    cout<<tree[1];
    for(int j = 2;j <= N;j++)
        cout<<" " <<tree[j];
}