[Title Description:
Binary sort tree or an empty tree or a binary tree having the following properties:
(1) If the left subtree is not empty, then the value of the left sub-tree, all the nodes are less than the value of the root;
(2) If the right subtree is not empty, the value of the right sub-tree, all nodes have a value greater than its root node;
(3) left and right sub-trees are binary sort tree;
(4) does not equal the node key.
Complete binary tree: only the bottom two layers of the node can be less than 2 degrees, and the bottom layer of the binary tree nodes are concentrated in a plurality of positions of the leftmost layer.
Given number N, and this number N 1 to N of a rearrangement. Now you need in order to build a binary sort tree, and output it in a hierarchical manner to traverse, and then determine whether it is a complete binary tree.
[Input Description:
Input contains two lines. The first line a positive integer N;. 1 to N arranged in the second row.
[Output] Description:
Comprising two output lines. The first level of behavior to build a binary sort tree traversal; second row to determine whether the complete binary tree: If the output yes, otherwise output no.
Sample input [1]:
10
7 9 8 4 6 2 10 1 5 3
[1] sample output:
7 4 9 2 6 8 10 1 3 5
yes
Sample input [2]:
5
3 4 5 2 1
[2] sample output:
3 2 4 1 5
no
[Sample] Description:
Example 1: /
Sample 2: /
Please download the unseen pictures
[Time limit, and the range of data Description:
Time: 1s space: 128M
To 100% of the data, 1≤N≤20
Thinking
A first read that the first number is the root of the tree, and a number for each read, sequentially comparing the node already exists (see build function);
And then from the first node scans, if there is no 0 of the output node;
Code:
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int N=1000010; bool flag; int tree[N]; int n,num,ma; void build(int jd) { int tot=1; while(1) { if(jd>tree[tot]) { tot<<=1; tot++; if(!tree[tot]) { tree[tot]=jd; break; } }else{ tot<<=1; //tot++; if(!tree[tot]) { tree[tot]=jd; break; } } } ma=max(ma,tot); } int main() { scanf("%d",&n); for(int i=1; i<=n; i++) { scanf("%d",&num); if(i==1) { tree[i]=num; continue; } build(num); } for(int i=1; i<=ma; i++) { if(!tree[i]) flag=1; else printf("%d ",tree[i]); } printf("\n"); if(!flag) printf("yes\n"); else printf("no\n"); return 0; }