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 NNN (≤1000\le 1000≤1000). Then NNN 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
思路:
1、首先因为是完全二叉树,因此可以用数组来存,既方便又不浪费空间,而且数组就是按层次遍历的顺序存的,最后只要把数组顺序输出就行了。
2、因为又是二叉搜索树,所以左边的结点一定小于根结点;再根据完全二叉树的性质,能够算出根节点是哪个元素
3、用分而治之的方法,先求出整棵树的根结点;然后再分别求左子树的根结点,再求右子树的根节点。
注意点:
如何根据二叉搜索树和完全二叉树的性质,来求出根结点
1、完全二叉树,知道了结点个数,就能确定整棵树的形状;因而能求出左子树有多少个结点
2、二叉搜索树,左边的结点一定小于根结点,又因为左边的结点个数L已经算出,只要将所给的元素从小到大排序,第L+1个就是根结点。
#include <stdlib.h> #include <stdio.h> #include <math.h> int arr[1005], rearr[1005]; int compare( const void* a, const void* b ){ return *(int*)a - *(int*)b; } int getLeftLength(int n){ //利用二叉树的性质:满二叉树第i层有 2^(i-1) 个结点, 高为h的满二叉树有 2^h - 1 个结点(从1开始) double h, x, L, t; h = (double)(int)( log((double)n+1) / log(2.0) ); //h = floor( log((double)n+1) / log(2.0) ); x = n - pow(2.0, h) + 1 ; t = pow(2.0, h - 1.0); x = x < t ? x : t; L = t - 1 + x; return (int)L; } void solve( int left, int right, int root ){ //初始调用: solve(0, n-1, 0); int n, L, leftRoot, rightRoot; n = right - left + 1; //数组中的总个数 if(n == 0) return ; //递归退出的条件 L = getLeftLength(n); //计算出左子树的结点 rearr[root] = arr[left + L]; //将新的根结点放入新的数组 leftRoot = root * 2 + 1; //左孩子 rightRoot = leftRoot + 1; //右孩子 solve(left, left + L - 1, leftRoot); solve(left + L + 1, right, rightRoot); } int main(){ int n; scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d", &arr[i]); } qsort(arr, n, sizeof(int), compare); solve(0, n-1, 0); for(int i = 0; i < n; i++){ if( i != 0 ) printf(" "); printf("%d", rearr[i]); } system("pause"); return 0; }