【题解】1115 Counting Nodes in a BST (30分)⭐⭐ 【BST】
发布日期:2021-06-29 16:14:55
浏览次数:2
分类:技术文章
本文共 1290 字,大约阅读时间需要 4 分钟。
题意:
按照输入序列建一颗二叉搜索树,输出最下面一层和倒数第二层点数之差
题解:
BST基础题,范围比较大,不能用数组模拟,用指针来写
#includeusing namespace std;#define ms(x, n) memset(x,n,sizeof(x));typedef long long LL;const int INF = 1 << 30;const int MAXN = 100010;struct node{ node *l, *r; int v, depth; node(node *ll, node *rr, int vv){ l = ll, r = ll, v = vv;}};int maxDepth = 0, n1 = 0, n2 = 0;node* Insert(node *root, int v){ if(root == NULL) root = new node(NULL, NULL, v); else if(v <= root->v) root->l = Insert(root->l, v); else root->r = Insert(root->r, v); return root;}void setDepth(node *root, int d){ root->depth = d; maxDepth = max(maxDepth, d); if(root->l) setDepth(root->l, d+1); if(root->r) setDepth(root->r, d+1);}void Dfs(node *root, int d){ if(root->depth == maxDepth) ++n1; else if(root->depth == maxDepth-1) ++n2; if(root->l) Dfs(root->l, d+1); if(root->r) Dfs(root->r, d+1);}int main() { ios::sync_with_stdio(false); int v, n; cin >> n >> v; node *root = new node(NULL, NULL, v); for(int i = 2; i <= n; ++i) cin >> v, Insert(root, v); //1为根节点 setDepth(root, 1); Dfs(root, 1); cout << n1 << " + " << n2 << " = " << n1+n2 << endl; return 0;}//6 5 4 6 2 1 7
转载地址:https://suprit.blog.csdn.net/article/details/104166968 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月14日 23时57分49秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
RecyclerView Item 行高定义无效的BUG
2019-04-30
markdown发生HTML渲染组件出错的解决方案
2019-04-30
android ScrollView嵌套WebView高度为0的BUG
2019-04-30
android 混淆代码后 app 运行报错时, 如何精准定位报错位置
2019-04-30
android 定位并通过百度在线查询详细地址教程
2019-04-30
android TextView 首行缩进与部分文字改变颜色大小效果
2019-04-30
android app 优化启动体验, 不闪白屏并且快速展示 splash
2019-04-30
INSTALL_FAILED_NO_MATCHING_ABIS 解决方案
2019-04-30
android 把打好的 apk 包通过 adb 的方式安装到手机上
2019-04-30
区块链学习之路[持续更新]
2019-04-30
RecycleView-Java.lang.IllegalArgumentException: Called attach on a child which is not detached
2019-04-30
AI学习笔记 (一) 手写识别
2019-04-30
七牛云图片外链失效的解决办法
2019-04-30
[Vue warn]: Invalid prop: type check failed for prop “src“. Expected String, Object, got Module
2019-04-30
Laravel 8 整合 Vue 2 解决 history 路由模式 404 问题
2019-04-30
MongoDB 小试牛刀--创建数据库和用户
2019-04-30