題目
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
題目大意
創(chuàng)建二叉搜索樹,且該樹同時為完全二叉樹。
思路
創(chuàng)建BST一般方法是鏈表插入,但注意到是完全二叉樹,其特殊性質(zhì)是在數(shù)組中,若根節(jié)點下標為i,則2i為左子樹根節(jié)點下標,2i+1為右子樹根結(jié)點下標(兩下標皆不超過節(jié)點數(shù)n),所以可以考慮使用數(shù)組進行創(chuàng)建比較簡便。
顯然BST的中序遍歷是有序的,在構(gòu)造完全二叉樹的時候按中序構(gòu)造即可(注意要先進行排序)。
代碼實現(xiàn)
#include <stdio.h>
#include <stdlib.h>
#define maxSize 1001
int tree[maxSize]; // 存放完全二叉搜索樹
int node[maxSize]; // 存放節(jié)點信息
int root, pos; // 樹中根節(jié)點下標,存儲節(jié)點下標
int n;
/*qsort比較函數(shù)*/
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
/*tree數(shù)組輸出,即為層次遍歷輸出*/
void print(int a[], int n)
{
int flag = 0;
int i;
for (i = 1; i <= n; ++i)
{
if(!flag)
{
flag = 1;
printf("%d", a[i]);
}
else
printf(" %d", a[i]);
}
}
/*創(chuàng)建CBST*/
void build(int root)
{
if (root > n)
return;
int lchild = root * 2;
int rchild = root * 2 + 1;
/*關(guān)鍵步驟,中序遍歷建樹*/
build(lchild);
tree[root] = node[pos++]; // 按序?qū)⒋鎯Φ慕Y(jié)點插入樹中
build(rchild);
}
int main(void)
{
int i;
scanf("%d", &n);
for(i = 1; i <= n; ++i)
scanf("%d", &node[i]);
qsort(&node[1], n, sizeof(int), cmp);
pos = 1;
build(1);
print(tree, n);
return 0;
}
參考