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.
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define Max 1000
class Tree{
public:
int a[Max];
int last;
};
Tree* T = new Tree; //建立一颗空的二叉搜索树
void createBinaryTree(int p[], int left, int right, int TRoot);
int getLeftSon(int n);
int main()
{
int N;
int p[Max];
cin >> N;
T->last = N;
for(int i = 0; i < N; i++){
cin >> p[i];
}
sort(p, p + N);
createBinaryTree(p, 0, N - 1, 0); //树的根节点在下标为0的位置开始
//层序遍历
for(int i = 0; i < T->last; i++){
if(i == 0) cout << T->a[0];
else cout << " " << T->a[i];
}
return 0;
}
int getLeftSon(int n){ //计算左子树结点个数
int l, h, i;
for(i = 0; pow(2, i) <= n; i++); //满二叉树结点数为pow(2, h) - 1
h = i - 1; //表示树的最大高度 - 1
l = n + 1 - pow(2, h); //表示最后一层的结点数
if(l > pow(2, h - 1)) //如果最后一层结点数超过一半,左子树结点个数为pow(2, h) - 1;
return pow(2, h) - 1;
else //没超过一半,右子树结点个数为pow(2, h - 1)
return n- pow(2, h - 1);
}
void createBinaryTree(int p[], int left, int right, int TRoot)
{
int n = right - left + 1; //总的元素个数
if(n == 0) return;
int l = getLeftSon(right - left + 1);
T->a[TRoot] = p[left + l];
createBinaryTree(p, left, left + l - 1, TRoot * 2 + 1); //左子树递归
createBinaryTree(p, left + l + 1, right, TRoot * 2 + 2); //右子树递归
}