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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define SIZE 1000
void InorderTree(int *T,int N);
void PrintTree(int *T,int N);
void CBTBuild(int Aleft,int Aright,int Troot);
int GetLeftLength(int N);
int A[SIZE],T[SIZE];
int main()
{
/* 初始定义两个数组,存放当前数据的数组A以及结果数组T 1.A:读入初始序列 2.A:按照大小排序 3.计算出左子树结点个数,右子树结点个数,找到当前结果完全二叉树T结点对应在A的下标并赋值 4.递归调用第三步,直到N个数均遍历完成 5.输出结果 */
int N;
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%d",&A[i]);
}
InorderTree(A,N);
CBTBuild(0,N-1,0);
PrintTree(T,N);
return 0;
}
void InorderTree(int *TREE,int N)
{
int swap,temp;
for(int i=0;i<N;i++)
{
swap = 1;
for(int j=0;j<N-i-1;j++)
{
if(TREE[j]>TREE[j+1])
{
swap = 0;
temp = TREE[j];
TREE[j] = TREE[j+1];
TREE[j+1] = temp;
}
}
if(swap) break;
}
}
void PrintTree(int *TREE,int N)
{
for(int i=0;i<N-1;i++){
printf("%d ",TREE[i]);
}
printf("%d\n",TREE[N-1]);
}
void CBTBuild(int Aleft,int Aright,int Troot)
{
int LeftRoot,RightRoot;
int n = Aright - Aleft +1;
if(n==0) return;
int L = GetLeftLength(n);
T[Troot] = A[Aleft+L];
LeftRoot = Troot*2+1; //Troot左孩子下标
RightRoot = LeftRoot+1; ////Troot右孩子下标
CBTBuild(Aleft,Aleft+L-1,LeftRoot);
CBTBuild(Aleft+L+1,Aright,RightRoot);
}
int GetLeftLength(int N)
{
int X,H,i =0;
while(pow(2,i)-1<N)
{
i++;
}
H = i-1;
X = N-pow(2,H)+1;
if(X<=pow(2,H-1))
return X+pow(2,H-1)-1;
else
return pow(2,H)-1;
}