04-树6 Complete Binary Search Tree (30分)
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 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
题目思路:
要求构造完全二叉排序树,如果直接采用普通的建树方式,挺麻烦,可以
利用了数据结构中完全二叉树的的一个性质:孩子节点的下标为i则其左孩子节点的下标为2*i,右孩子节点的下标为2*i+1,这个性质只有完全二叉树才满足。
#include<stdio.h>
#include<stdlib.h>
#define Naxsize 1000
void solve(int Aleft, int Aright,int TRoot, int A[],int T[]);
int compare(const void *a, const void *b);
int Get_Left_Nodes(int n);
int Min(int a, int b);
int main()
{
//freopen("test.txt", "r", stdin);
//一共多少个节点
int N;
scanf("%d\n",&N);
//接收收入的节点
int A[N],T[N];
for(int i = 0; i < N; i++)
{
scanf("%d",&A[i]);
}
//调整为完全二插搜索树,
//排序成中序遍历
qsort(A,N,sizeof(int),compare);
int ALeft = 0, ARight = N -1, TRoot = 0;
solve(ALeft, ARight, TRoot, A, T);
//输出
for (int i = 0; i < N; ++i){
if(i == 0){
printf("%d", T[i]);
}
else
printf(" %d", T[i]);
}
return 0;
}
int compare(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
void solve(int Aleft, int Aright, int TRoot,int A[],int T[])
{
/*初始调用为*solve(0,N-1,0)*/
int n;
//看这里面还有元素嘛
n = Aright - Aleft+1;
if(n == 0)
{
return;
}
//计算出n个节点的树其左子树有多少个节点
int L,LeftRoot,RightRoot;
L = Get_Left_Nodes(n);
T[TRoot] = A[Aleft + L];//根节点的值
//在堆里面,开始的下标是1,0不存在真实值,所以左儿子是2i,这里是2i+1
LeftRoot = TRoot * 2 + 1;
RightRoot = LeftRoot + 1;
solve(Aleft,Aleft+L-1,LeftRoot,A,T);
solve(Aleft+L+1,Aright,RightRoot,A,T);
}
int Get_Left_Nodes(int n)
{
int H = 0, tmp = 1, X, L;//X为左子树最下一层的结点数
int N = n;
while(N > 1){
N /= 2;
H++;//树的高度
}
for (int i = 0; i < H - 1; ++i){
tmp *= 2;
}
X = n - 2 * tmp + 1;
X = Min( X, tmp );
L = tmp - 1 + X;
return L;
}
int Min(int a, int b)
{
return (a < b) ? a : b;
}