pat1064. Complete Binary Search Tree (30)
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 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
#include<cstdio>
#include<stack>
#include<algorithm>
#include<iostream>
#include<stack>
#include<set>
#include<map>
#include<cmath>
using namespace std;
int line[],tree[];
void Build(int *line,int *tree,int n,int cur){
if(!n){
return;
}
int h=log(n)/log();
int x=n-(pow(,h)-); //cout<<"x: "<<x<<endl; if(x>pow(,h-)){
x=pow(,h-);
} //cout<<"x: "<<x<<endl; int l=pow(,h-)+x-; //cout<<"l: "<<l<<endl; tree[cur]=line[l];
Build(line,tree,l,cur*+);
Build(line+l+,tree,n-l-,cur*+);
}
int main(){
//freopen("D:\\INPUT.txt","r",stdin);
int n,i;
scanf("%d",&n);
for(i=;i<n;i++){
scanf("%d",&line[i]);
}
sort(line,line+n);
Build(line,tree,n,);
printf("%d",tree[]);
for(i=;i<n;i++){
printf(" %d",tree[i]);
}
printf("\n");
return ;
}
最新文章
- SpringMVC 数据校验
- C#与C++的发展历程第一 - 由C#3.0起
- VS插件开发 - 登录身份验证
- B树、B-树、B+树、B*树
- linux进程命令
- android获得图片
- Hello World(本博客启程篇)
- javase基础笔记2——数据类型和面向对象
- linux 输入java 出现中文乱码
- php ajax提交post请求出现数组被截断情况的解决方法
- hadoop相关问题
- openstack API debug OpenstackEveryProject_CLI,curl_based
- BON取代半岛电视,美国人要“换口味”了吗?
- WPF 使用DMSkin for WPF 快速搭建漂亮的WPF程序
- java.sql.SQLException: Incorrect string value: &#39;\xE5\xBC\xA0\xE9\x9B\xB7&#39; for column &#39;content&#39; at row 1
- CRM之分页
- 动态编程(Dynamic Programming)
- python 为空判断场景
- innerHTML和innerText的区别,以及select元素中怎么取出被选中的option。
- OpenEXR-2.2.0在Win7 x64系统下的安装方法