当前位置:网站首页>是否完全二叉搜索树 (30 分)
是否完全二叉搜索树 (30 分)
2022-04-23 08:35:00 【怀化第二深情】
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过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
#include<bits/stdc++.h>
using namespace std;
vector<int> level(100010, -1);
int n, t, flag, st, cnt;
void build(int val, int root){
if(val > level[root]){
if(level[2 * root + 1] != -1) build(val, 2 * root + 1);
else level[2 * root + 1] = val;
}
else if(val < level[root]){
if(level[2 * root + 2] != -1) build(val, 2 * root + 2);
else level[2 * root + 2] = val;
}
}
int main(){
cin >> n >> t, level[0] = t;
for(int i = 1;i < n;i++) cin >> t, build(t, 0);
for(int i = 0;i < 100010;i++){
if(level[i] != -1){
if(flag++) cout << " ";
cout << level[i];
cnt++;
}else{
if(cnt < n) st = 1;
}
}
if(st) cout << endl << "NO";
else cout << endl << "YES";
}
版权声明
本文为[怀化第二深情]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dege2929512534/article/details/124339375
边栏推荐
猜你喜欢

洋桃电子STM32物联网入门30步笔记三、新建CubeIDE工程和设置讲解

第一性原理 思维导图

信息收集相关知识点及题解

Consensus Token:web3.0生态流量的超级入口

四张图弄懂matplotlib的一些基本用法

CGM optimizes blood glucose monitoring and management -- Yiyu technology appears in Sichuan International Medical Exchange Promotion Association

Reference passing 1

Noyer électronique stm32 Introduction à l'Internet des objets 30 étapes notes I. différences entre la Bibliothèque Hal et la Bibliothèque standard

虚拟线上展会-线上vr展馆实现24h沉浸式看展

bashdb下载安装
随机推荐
STM32 uses Hal library. The overall structure and function principle are introduced
What is RPC
ESP32程序下载失败,提示超时
完全二叉搜索树 (30 分)
word加水印
Notes on 30 steps of introduction to Internet of things of yangtao electronics STM32 III. Explanation of new cubeide project and setting
2022-04-22 OpenEBS云原生存储
xctf刷题小记
洋桃电子STM32物联网入门30步笔记三、新建CubeIDE工程和设置讲解
洋桃电子STM32物联网入门30步笔记三、CubeMX图形化编程、设置开发板上的IO口
LeetCode396.旋转数组
对li类数组对象随机添加特性,并进行排序
Test your machine learning pipeline
数据可视化:使用Excel制作雷达图
Failed to convert a NumPy array to a Tensor(Unsupported Object type int)
洋桃电子STM32物联网入门30步笔记二、CubeIDE下载、安装、汉化、设置
Let the earth have less "carbon" and rest on the road
An example of network communication based on TCP / IP protocol -- file transmission
JVM工具之Arthas使用
Go语言自学系列 | golang结构体指针