1064. Complete Binary Search Tree (30) time limit MS Memory limit 65536 KB code length limit 16000 B procedure StandardAuthor Chen, Yue
A binary Search Tree (BST) is recursively defined as a Binary Tree which have 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 is binary search trees.
A complete Binary tree (CBT) was a tree that was completely filled, with the possible exception of the bottom level, which I s filled from left to right.
Now given a sequence of distinct non-negative integer keys, a unique BST can being constructed if it is required that the Tre E must also be a CBT. You is supposed to output the level order traversal sequence of this BST.
Input Specification:
Each input file contains the one test case. For each case, the first line contains a positive integer N (<=1000). Then N distinct non-negative integer keys is given in the next line. All the numbers in a line is separated by a space and is 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 is separated by a space, and there must is no extra space at the end of the line.
Sample Input:
101 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
Submit Code
1#include <cstdio>2#include <stack>3#include <algorithm>4#include <iostream>5#include <stack>6#include <Set>7#include <map>8#include <cmath>9 using namespacestd;Ten intline[1005],tree[1005]; One voidBuild (int*line,int*tree,intNintcur) { A if(!N) { - return; - } the intH=log (n)/log (2); - intx=n-(POW (2, h)-1); - - //cout<< "x:" <<x<<endl; + - if(X>pow (2, H-1)){ +X=pow (2, H-1); A } at - //cout<< "x:" <<x<<endl; - - intL=pow (2, H-1) +x-1; - - //cout<< "L:" <<l<<endl; in -tree[cur]=Line[l]; toBuild (line,tree,l,cur*2+1); +Build (line+l+1, tree,n-l-1, cur*2+2); - } the intMain () { * //freopen ("D:\\input.txt", "R", stdin); $ intn,i;Panax Notoginsengscanf"%d",&n); - for(i=0; i<n;i++){ thescanf"%d",&line[i]); + } ASort (line,line+n); theBuild (Line,tree,n,0); +printf"%d", tree[0]); - for(i=1; i<n;i++){ $printf"%d", Tree[i]); $ } -printf"\ n"); - return 0; the}
pat1064. Complete Binary Search Tree (30)