Complete Binary Search Tree
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.
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
题意
创建二叉搜索树,且该树同时为完全二叉树。
思路
创建BST一般方法是链表插入,但注意到是完全二叉树,其特殊性质是在数组中,若根节点下标为i,则2i为左子树根节点下标,2i+1为右子树根结点下标(两下标皆不超过节点数n),所以可以考虑使用数组进行创建比较简便。
要想创建树,要么知道中序序列以及其他遍历序列中的一种,要么知道一种遍历序列以及树的整体框架,显然本题是后面一种。由于二叉查找树的中序遍历序列是有序的,且完全二叉树的空框架可以用数组表示,那么只要在中序遍历时依次填入数据,即可构建完全二叉查找树。
代码实现
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1001;
int cbt[maxn], n; // 完全二叉树框架,结点个数
int data[maxn], index = 0; // 结点数据,已使用结点个数
void inOrder(int i) // 中序遍历
{
if (i > n)
return;
inOrder(2 * i);
cbt[i] = data[index++]; // 访问根结点时填入数据
inOrder(2 * i + 1);
}
void levelOrder() // 层序遍历
{
bool flag = true; // flag用来控制空格输出
queue<int> q;
q.push(1);
while(!q.empty())
{
int now = q.front();
q.pop();
if (flag)
flag = false;
else
printf(" ");
printf("%d", cbt[now]);
if (2 * now <= n)
q.push(2 * now);
if (2 * now + 1 <= n)
q.push(2 * now + 1);
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &data[i]);
sort(data, data + n); // 读取完数据后排序,以便在中序遍历中使用
inOrder(1);
levelOrder();
return 0;
}