1064. Complete Binary Search Tree (30)
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.
Sample Input:10 1 2 3 4 5 6 7 8 9 0Sample Output:
6 3 8 1 5 7 9 0 2 4
先按照定义构建完全二叉树的框架,接下来就是把数字分别填到这颗二叉树的节点中,使得其满足二叉搜索树的定义。其实填入节点可以直接中序遍历这颗二叉树框架即可。
AC代码:
#define _CRT_SECURE_NO_DEPRECATE #pragma warning(disable:4996) #include<iostream> #include<string> #include<algorithm> #include<map> #include<cctype> #include<cmath> #include<cstring> #include<vector> #include<set> #include<queue> #include<limits.h> using namespace std; typedef long long ll; #define N_MAX 1000+5 #define INF 0x3f3f3f3f int n, a[N_MAX]; struct Node { int key; int l_child, r_child; Node(int key=INF,int l_child=INF,int r_child=INF):key(key),l_child(l_child),r_child(r_child) {} }node[N_MAX]; void init(int n) {//建立完全二叉树的框架 n--; int cur = 0; int flag = 0; while (n--) { if (!(flag & 1))node[cur].l_child = 2 * cur + 1; else { node[cur].r_child = 2*cur+2; cur++; } flag++; } } int cnt = 0; void inorder(int n) { if(node[n].l_child!=INF)inorder(node[n].l_child); node[n].key = a[cnt++]; if(node[n].r_child!=INF)inorder(node[n].r_child); } vector<int>vec; void bfs() { queue<int>que; que.push(0); while (!que.empty()) { int p = que.front(); que.pop(); vec.push_back(node[p].key); if (node[p].l_child != INF)que.push(node[p].l_child); if (node[p].r_child != INF)que.push(node[p].r_child); } } int main() { while (scanf("%d", &n) != EOF) { for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } sort(a,a+n); init(n); cnt = 0; inorder(0); bfs(); for (int i = 0; i < vec.size();i++) { printf("%d%c",vec[i],i+1==vec.size()?'\n':' '); } } return 0; }