A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
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 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
题目大意:给出二叉搜索树的一个序列,如果这棵树还要求是完全二叉树的话,这棵树就是唯一的。现在要输出这棵树的层序遍历。
思路:要用到二叉搜索树、完全二叉树两种树的特性:
- 二叉搜索树:键值从小到大排为中序遍历
- 完全二叉树:若用从1开始的数组存,对于一个索引为index的结点来说,index2为其左儿子,index2+1为其右二子。
根据这两点,先将序列从小到大排序,然后在数组中按照中序遍历建树,最后BFS。
代码如下:
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef struct node* bst;
int sum = 1;//现在是数组中第几个数被插入树中
struct node
{
int data;
bst left;
bst right;
};
bst build(int a[], int index, int n)
{
if(index > n) return NULL;
bst t = new node;
t->left = build(a, index*2, n);
t->data = a[sum++];
t->right = build(a, index*2+1, n);
return t;
}
void bfs(bst t, int n)
{
queue<bst>q;
q.push(t);
int cnt = 0;
while(!q.empty())
{
bst x = q.front();
cnt ++;
if(cnt == n) cout << x->data;
else cout << x->data << " ";
if(x->left) q.push(x->left);
if(x->right) q.push(x->right);
q.pop();
}
cout << endl;
}
int main()
{
int n, a[1001];
cin >> n;
int i;
for(i=1; i<=n; i++) cin >> a[i];
sort(a+1, a+1+n);
bst t = build(a, 1, n);
bfs(t, n);
return 0;
}