L3-010. 是否完全二叉搜索树
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
通过线段树的构建方法对所有点建二叉搜索树,则可在构建了一棵无键值节点均为0的完全二叉树。之后通过层次遍历判断这棵树在遍历完这n个节点的过程中是否出现为空的叶子节点判断是否是完全二叉搜索树。
#include <stdio.h>
#include <iostream>
using namespace std ;
#define MAX 1<<20
int tree[MAX] = {0} ,num , n;
void build(int a)
{
if(tree[a]==0) tree[a] = num;
else if(num < tree[a])
build(a<<1|1);
else build(a << 1);
}
int main()
{
int flag = 0 ;
scanf("%d" , &n) ;
for(int i = 0 ; i < n ; i ++)
{
scanf("%d" , &num) ;
build(1) ;
}
int cnt = 1;
for(int i = 1 ; cnt <= n ; i ++)
{
if(tree[i] == 0) flag = 1;
else
{
if(cnt == n) printf("%d\n" , tree[i]);
else printf("%d " , tree[i]);
cnt ++ ;
}
}
if(!flag) printf("YES\n");
else printf("NO\n");
return 0 ;
}