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;
}