04-树6 Complete Binary Search Tree
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 (≤). 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 0Sample Output:
6 3 8 1 5 7 9 0 2 4
1 //二叉搜索树左小右大的有序特征使它中序遍历得到的是一个从小到大的有序序列; 2 //完全二叉树中,如果一个结点的序号为i,它的左子结点序号为2*i,右子结点的序号为2*i+1; 3 //结合以上两个规律,我们就能通过排序得到该数的中序遍历序列 4 //通过中序序列和完全二叉树的特点得到层序遍历序列 5 #include<stdio.h> 6 #include<algorithm> 7 using namespace std; 8 9 bool cmp(int a, int b){ 10 return a<b; 11 } 12 13 void LevleTraNode(int *a, int *b, int now, int N, int *i) { 14 //now是a[*i]在层序遍历序列中的序号,注意层序遍历的序号是从1~N+1 15 //*i是a[]的下标,传入的是指针,以记录其改变 16 if(now<N){ 17 LevleTraNode(a, b, now*2, N, i); 18 b[now] = a[(*i)++]; 19 LevleTraNode(a, b, now*2+1, N, i); 20 } 21 } 22 23 int main( ){ 24 int N; 25 scanf("%d", &N); 26 int a[N], b[N+1]; 27 for(int i=0; i<N; i++){ 28 scanf("%d", &a[i]); 29 } 30 sort(a, a+N, cmp); //从小到大排序,得到中序遍历序列 31 int j=0; 32 LevleTraNode(a, b, 1, N+1, &j); 33 for(int i=1; i<N+1; i++){ 34 if(i>1) printf(" "); 35 printf("%d", b[i]); 36 } 37 printf("\n"); 38 return 0; 39 }

浙公网安备 33010602011771号