L3-010. 是否完全二叉搜索树
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出“YES”,如果该树是完全二叉树;否则输出“NO”。
输入样例1:9 38 45 42 24 58 30 67 12 51输出样例1:
38 45 24 58 42 30 12 67 51 YES输入样例2:
8 38 24 12 45 58 67 42 51输出样例2:
38 45 24 58 42 12 67 51 NO
解题思路
创建二叉搜索树,利用数组就可以,下标为节点编号,对于完全二叉树的判断。只要前n个节点分别是输入的n个数,就是完全二叉树
代码:
#include <iostream>
#include <cstdio>
#include <map>
#include <cmath>
#include <string.h>
#include <algorithm>
#include <set>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
const int maxn = 30;
const int INF = 0x3f3f3f3f;
int n,x;
int tree[1<<20];///这里因为可能每一层只有一个数
void build(int node){
if(tree[node] == 0) tree[node] = x;
else if(x > tree[node]) build(node*2);
else build(node*2+1);
}
int main()
{
scanf("%d",&n);
for(int i = 0; i<n;++i){
scanf("%d",&x);
build(1);
}
bool f = true;
for(int i = 1,cnt = 1; cnt <=n; ++i){
if(tree[i] == 0) f = 0;
else{
printf("%d",tree[i]);
if(cnt != n) printf(" ");
cnt++;
}
}
if(f) printf("\nYES");
else printf("\nNO");
return 0;
}