是否完全二叉搜索树 (30分)
来源:互联网 发布:在线看熊片的软件 编辑:程序博客网 时间:2024/05/01 13:32
L3-010. 是否完全二叉搜索树
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出“YES”,如果该树是完全二叉树;否则输出“NO”。
输入样例1:938 45 42 24 58 30 67 12 51输出样例1:
38 45 24 58 42 30 12 67 51YES输入样例2:
838 24 12 45 58 67 42 51输出样例2:
38 45 24 58 42 12 67 51NO
#include <bits/stdc++.h>using namespace std;int n;struct node{ int data; int id; struct node * l, *r;};struct node *creat(int x,struct node *root){ if(root == NULL) { struct node *t; t= new node; t->data = x; t->l = t->r = NULL; return t; } if(root->data < x) root->l = creat(x, root->l); else root->r = creat(x, root->r); return root;};void in(struct node *root){ if(root) { printf("%d ",root->data); in(root->l); in(root->r); }}int ff;void bfs(struct node *root){ queue<node *>q; root->id = 1; q.push(root); int flag = 0; while(!q.empty()) { if(flag) printf(" "); struct node *now = q.front(); q.pop(); flag = 1; if(now->id > n) ff = 1; printf("%d",now->data); if(now->l != NULL) { now->l->id = now->id<<1; q.push(now->l); } if(now->r != NULL) { now->r->id = now->id<<1|1; q.push(now->r); } } printf("\n");}int main(){ struct node *root; root = new node; root = NULL; ff = 0; scanf("%d", &n); for(int i = 1; i <= n; i++) { int x; scanf("%d", &x); root = creat(x,root); } ff = 0; bfs(root); if(ff) printf("NO\n"); else printf("YES\n");}
0 0
- 是否完全二叉搜索树 (30分)
- 5-13 是否完全二叉搜索树 (30分)
- 7-13 是否完全二叉搜索树(30 分)
- 7-2 是否完全二叉搜索树(30 分)
- 7-2 是否完全二叉搜索树(27 分)
- PTA 7-2 是否完全二叉搜索树(30 分)
- 是否完全二叉搜索树
- 是否二叉搜索树(25 分)
- 是否二叉搜索树(25 分)
- L3-010. 是否完全二叉搜索树
- PATL3-010. 是否完全二叉搜索树
- 14 是否完全二叉搜索树
- L3-010. 是否完全二叉搜索树
- L3-010. 是否完全二叉搜索树
- 5-13 是否完全二叉搜索树
- 天梯赛-是否完全二叉搜索树
- L3-010.是否完全二叉搜索树
- L3-010. 是否完全二叉搜索树
- 在window平台下的git push出现Permission denied (publickey).
- 问题E 铺地毯 [模拟]
- 【OpenCV学习笔记】二、OpenCV例程赏析
- excel文档导入到mysql数据库
- c语言 常见内存错误
- 是否完全二叉搜索树 (30分)
- 爱拼宝宝,电商小程序
- UEFI启动模式下安装Ubuntu 16.04教程
- leet_257. Binary Tree Paths-根到叶子的路径
- 数据结构实验之链表九:双向链表
- [博弈论] cf317 D Game with Powers
- LeetCode 104. Maximum Depth of Binary Tree 题解
- 今天开始陆陆续续写博客,做更优秀的程序员
- maven的安装