题目

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<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#define MaxSize 2005
using namespace std;
int value[MaxSize];
int BST[MaxSize];

// 计算 n 个结点的树其左树结点个数 
int getLeftTreeSize(int n){
	int h =0;   // 保存该结点下满二叉树的层数 
	int tmp = n+1;
	while(tmp!=1){
		tmp /=2;
		h++;
	}
	int x = n-pow(2,h)+1;   // 最下面一排子叶结点个数 
	x = x<pow(2,h-1)?x:pow(2,h-1);   // 子叶结点个数最多是 2^(h-1) 
	int L = pow(2,h-1)-1+x;   // 该结点个数情况下左子树的个数 
	return L;
}

// 填充函数
void fill(int left,int right,int root){
	int n = right - left + 1;  // 确定范围内数值个数 
 	if(!n)
 		return;
 	int L = getLeftTreeSize(n);   // 找到"偏移量" 
 	BST[root] = value[left + L];    // 根结点的值应该是 左边界值 + 偏移量 
 	int leftRoot = 2 * root + 1;   // 左儿子结点位置,由于从 0 开始 
 	int rightRoot = leftRoot + 1;  // 右儿子结点位置 
 	fill(left,left+L-1,leftRoot);  // 左子树递归 
 	fill(left+L+1,right,rightRoot);   // 右子树递归 
}

int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>value[i];
	}
	// 从小到大排序 
	sort(value,value+n);
	fill(0,n-1,0);
	for(int i=0;i<n;i++){
		if(i)
			cout<<" ";
		cout<<BST[i];
	}
	return 0;
}