PAT_A1064#Complete Binary Search Tree
Source:
Description:
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 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
Keys:
- 完全二叉树(Complete Binary Tree)
- 二叉查找树(Binary Search Tree)
- 二叉树的建立
- 二叉树的遍历
Attention:
- 很好的一道题,全面考察了完全二叉树和二叉查找树的性质
Code:
1 /* 2 Data: 2019-06-26 16:48:26 3 Problem: PAT_A1064#Complete Binary Search Tree 4 AC: 13:22 5 6 题目大意: 7 BST定义:lchild < root <= rchild 8 给定一个序列,建立CBT和BST,打印层次遍历 9 10 基本思路: 11 一维数组作为CBT的存储结构,结点序号从1~N; 12 中序遍历CBT,结果递增有序,因此遍历的同时依次赋值排序好的键值即可; 13 CBT树的遍历:左子树=i*2,右子树=i*2+1,空树i>n 14 CBT的层次遍历:打印cbt[1]~cbt[n]即可 15 */ 16 #include<cstdio> 17 #include<queue> 18 using namespace std; 19 const int M=1e3+10; 20 int cbt[M],n,x; 21 priority_queue<int,vector<int>,greater<int> > bst; 22 23 void InOrder(int root) 24 { 25 if(root > n) 26 return; 27 InOrder(root*2); 28 cbt[root] = bst.top(); 29 bst.pop(); 30 InOrder(root*2+1); 31 } 32 33 int main() 34 { 35 #ifdef ONLINE_JUDGE 36 #else 37 freopen("Test.txt", "r", stdin); 38 #endif // ONLINE_JUDGE 39 40 scanf("%d", &n); 41 for(int i=0; i<n; i++) 42 { 43 scanf("%d", &x); 44 bst.push(x); 45 } 46 InOrder(1); 47 for(int i=1; i<=n; i++) 48 printf("%d%c", cbt[i],i==n?'\n':' '); 49 50 return 0; 51 }