您的位置:首页 > 其它

1064. Complete Binary Search Tree (30)

2016-03-06 23:16 337 查看

1064. Complete Binary Search Tree (30)

时间限制100 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
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.<
b34a
/li>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
中序遍历完全搜索二叉树 必定得到一个有序的序列,所有先建立一个完全二叉树,中序遍历得到地址数组,然后按照数据从小到大依次填入即可.
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<map>
#include<string.h>
#include<stack>
using namespace std;
struct Node{
int data;
Node *left,*right;
Node():data(0),left(NULL),right(NULL){};
};
void Inorder(Node * T,vector<Node *>&ans){
if(T->left)
Inorder(T->left, ans);
if(T)
ans.push_back(T);
if(T->right)
Inorder(T->right, ans);
}
int main(){
int n,count=0;
cin>>n;
vector<int>nums(n);
for (int i=0; i<n; ++i) {
cin>>nums[i];
}
if(n==1)
{
printf("%d\n",nums[0]);
return 0;
}
sort(nums.begin(), nums.end());
Node * root =NULL;
queue<Node *>q;
root = new Node;
count++;
if(root)
q.push(root);
while (!q.empty()) {//建立完全二叉树
Node * p = q.front();
q.pop();
p->left = new Node;
count ++;
if(count==n)
break;
q.push(p->left);
p->right = new Node;
count++;
if(count==n)
break;
q.push(p->right);
}
vector<Node *>ans;
Inorder(root, ans);
for(int i=0;i<ans.size();++i){
ans[i]->data = nums[i];
}
queue<Node *> level;
if(root)
level.push(root);
vector<int>o;
while (!level.empty()) {
Node * p = level.front();
level.pop();
o.push_back(p->data);
if(p->left)level.push(p->left);
if(p->right)level.push(p->right);
}
for (int i=0; i<o.size(); i++) {
printf(i==o.size()-1?"%d\n":"%d ",o[i]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: