時間限制
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.
Input Specification:
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.
Output Specification:
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 0Sample Output:
6 3 8 1 5 7 9 0 2 4
解題思路(轉載):
這個題目要求構造完全二叉排序樹,如果直接採用普通的建樹方式,其實挺麻煩的,我剛開始也是那樣做得到,還調試了很久,AC了,但今天突然在網上看到別人做的這個題思路非常的好,所以消化吸收後寫了下,其實就是利用了數據結構中完全二叉樹的的一個性質:孩子節點的下標爲i則其左孩子節點的下標爲2*i,右孩子節點的下標爲2*i+1,這個性質只有完全二叉樹才滿足,其實反過來按這個性質構造出來的樹就是一個完全二叉樹。 要實現這棵完全二叉樹也是排序樹,其實就簡單了,顯然一棵二叉排序樹的中序遍歷序列是遞增有序的,所以這就簡單了,只要在構造完全二叉樹的時候按中序構造就可以了(前提是元素遞增有序)。
以前做樹的題目都是鏈接型的,而這個題目用完全二叉樹的這個性質確非常的合適,所以記錄下,供以後回顧學習。
<span style="font-size:18px;">#include <iostream>
#include <algorithm>
#define MAX 1001
using namespace std;
int node[MAX];
int tree[MAX];
int pos,n;
void InOrderBuild(int root)
{
if(root>n)
return;
int lchild = root<<1;
int rchild = (root<<1)+1;
InOrderBuild(lchild);
tree[root] = node[pos++];
InOrderBuild(rchild);
}
int main()
{
int i;
cin>>n;
for(i=0;i<n;i++)
cin>>node[i];
sort(node,node+n);
pos = 0;
InOrderBuild(1);
for(i=1;i<n;i++)
cout<<tree[i]<<" ";
cout<<tree[i]<<endl;
return 0;
}</span><span style="font-size:32px;color: rgb(255, 0, 0);">
</span>