博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT甲级——A1115 Counting Nodes in a BST【30】
阅读量:4541 次
发布时间:2019-06-08

本文共 2378 字,大约阅读时间需要 7 分钟。

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Insert a sequence of numbers into an initially empty binary search tree. Then you are supposed to count the total number of nodes in the lowest 2 levels of the resulting tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤) which is the size of the input sequence. Then given in the next line are the N integers in [which are supposed to be inserted into an initially empty binary search tree.

Output Specification:

For each case, print in one line the numbers of nodes in the lowest 2 levels of the resulting tree in the format:

n1 + n2 = n

where n1 is the number of nodes in the lowest level, n2 is that of the level above, and n is the sum.

Sample Input:

925 30 42 16 20 20 35 -5 28

Sample Output:

2 + 4 = 6
1 #include 
2 #include
3 #include
4 using namespace std; 5 struct Node 6 { 7 int v; 8 Node *l, *r; 9 Node(int a = -1) :v(a), l(nullptr), r(nullptr) {}10 };11 Node* root = nullptr;12 int n, level = -1, a;13 vector
res;14 void creatTree(Node*& root, int x)15 {16 if (root == nullptr)17 {18 root = new Node(x);19 return;20 }21 if (x <= root->v)22 creatTree(root->l, x);23 else24 creatTree(root->r, x);25 }26 void BFS(Node* root)27 {28 queue
q;29 q.push(root);30 while (!q.empty())31 {32 int num = 0;33 queue
temp;34 while (!q.empty())35 {36 Node* p = q.front();37 q.pop();38 num++;39 if (p->l != nullptr)40 temp.push(p->l);41 if (p->r != nullptr)42 temp.push(p->r);43 }44 q = temp;45 res.push_back(num);46 }47 }48 int main()49 {50 51 cin >> n;52 while (n--)53 {54 cin >> a;55 creatTree(root, a);56 }57 BFS(root);58 cout << res[res.size() - 1] << " + " << res[res.size() - 2] << " = " << res[res.size() - 1] + res[res.size() - 2] << endl;59 return 0;60 }

 

转载于:https://www.cnblogs.com/zzw1024/p/11457242.html

你可能感兴趣的文章
awk多模式匹配
查看>>
线段树
查看>>
a span等行内元素加margin属性后无效果解决方案
查看>>
傻瓜式硬盘重装win7系统图文加视频教程
查看>>
BZOJ 1607 [Usaco2008 Dec]Patting Heads 轻拍牛头:统计 + 筛法【调和级数】
查看>>
如果一个人请优雅的活着。
查看>>
验证码
查看>>
Django缓存配置
查看>>
Ubuntu下安装 Mysql
查看>>
LeetCode--Reverse Integer
查看>>
PHP_APC+Ajax实现的监视进度条的文件上传
查看>>
ZOJ2833*(并查集)
查看>>
外连接简要总结
查看>>
第一次作业-准备篇
查看>>
【C++】继承时构造函数和析构函数
查看>>
opencv源代码之中的一个:cvboost.cpp
查看>>
swift
查看>>
pycharm 快捷键
查看>>
Linux常用命令
查看>>
.net中的设计模式---单例模式
查看>>