标签:
A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
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
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <iostream> 4 #include <string.h> 5 #include <math.h> 6 #include <algorithm> 7 #include <string> 8 #include <stack> 9 #include <queue> 10 using namespace std; 11 const int maxn=1010; 12 int n,number[maxn],CBT[maxn]; 13 int shuzucount=0; 14 15 void inOrder(int root)//这里中序遍历的目的是, 16 {//将中序的结果数组num与过程结合,得到CBT 17 if(root>n)return; 18 inOrder(root*2); 19 CBT[root]=number[shuzucount++]; 20 inOrder(root*2+1); 21 } 22 int main(){ 23 scanf("%d",&n); 24 for(int i=0;i<n;i++) 25 { 26 scanf("%d",&number[i]); 27 } 28 sort(number,number+n); 29 inOrder(1); 30 for(int i=1;i<=n;i++) 31 { 32 printf("%d",CBT[i]); 33 if(i<n)printf(" "); 34 } 35 return 0; 36 }
A1064. Complete Binary Search Tree (30)
标签:
原文地址:http://www.cnblogs.com/ligen/p/4322579.html