To insert a sequence of given numbers into an initially empty binary search tree (defined as the left subtree with a large key and a right subtree with a small key), you need to determine whether the final tree is a complete binary tree, and give The result of its level-order traversal.
Input format:
The first line of input gives a positive integer up to 20 N
; the second line gives N
different positive integers separated by spaces.
Output format:
Insert the input N
positive integers sequentially into an initially empty binary search tree. In the first line, output the result of the hierarchical traversal of the result tree. The numbers are separated by 1 space, and there must be no extra spaces at the beginning and end of the line. The second line of output YES
, if the tree is a complete binary tree; otherwise output NO
.
Input sample 1:
9
38 45 42 24 58 30 67 12 51
Sample output 1:
38 45 24 58 42 30 12 67 51
YES
Input sample 2:
8
38 24 12 45 58 67 42 51
Sample output 2:
38 45 24 58 42 12 67 51
NO
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[100],b;
int n;
void add(int i,int d)
{
if(a[i] == -1)
{
a[i] = d;
return;
}
if(d > a[i])add(i*2,d);
else add(i*2+1,d);
}
int main()
{
scanf("%d",&n);
memset(a,-1,sizeof(a));
for(int i = 0;i < n;i ++)
{
scanf("%d",&b);
add(1,b);
}
int c = 0,i = 0;
while(c < n)
{
while(a[i] == -1)i++;
if(c)printf(" %d",a[i]);
else printf("%d",a[i]);
i ++;
c ++;
}
if(i == n + 1)printf("\nYES");
else printf("\nNO");
}