标签:
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 0Sample Output:
6 3 8 1 5 7 9 0 2 4
#include <iostream>
#include <vector>
#include<algorithm>
#include<math.h>
#include <queue>
using namespace std;
vector<int> num;
struct Node {
int val;
Node *left;
Node *right;
};
Node* BuildFullTree(int min, int n) {
if (n == 0) {
return NULL;
}
if (n == 1) {
Node *p = (Node*)malloc(sizeof(Node));
p->val = num[min];
p->left = NULL;
p->right = NULL;
return p;
}
int level = 1;
while (true)
{
if (pow(2, level) > n) {
level--;
break;
}
level++;
}
int leftCnt, rightCnt;
if (n + 1 - pow(2, level) < pow(2, level - 1))
leftCnt = n - pow(2, level - 1);
else
leftCnt = pow(2, level) - 1;
rightCnt = n - 1 - leftCnt;
Node *p = (Node*)malloc(sizeof(Node));
p->val = num[min+leftCnt];
p->left = BuildFullTree(min, leftCnt);
p->right = BuildFullTree(min+leftCnt + 1, rightCnt);
return p;
}
int main(void) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
num.push_back(temp);
}
sort(num.begin(), num.end());
Node *root = (Node*)malloc(sizeof(Node));
root = BuildFullTree(0, n);
queue<Node*> q;
q.push(root);
while (true)
{
if (q.front()->left != NULL)
q.push(q.front()->left);
if (q.front()->right != NULL)
q.push(q.front()->right);
cout << q.front()->val;
q.pop();
if (q.empty())
break;
cout << " ";
}
return 0;
}
1064. Complete Binary Search Tree (30)
标签:
原文地址:http://www.cnblogs.com/zzandliz/p/5023202.html