LeetCode 637. Average of Levels in Binary Tree(层序遍历)
2024-10-20 20:45:06
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
<b>Input:</b>
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
The range of node’s value is in the range of 32-bit signed integer.
分析
树的层序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> res;
double sum=0,cnt=0;
queue<TreeNode*> q;
q.push(root);
TreeNode* last=root;
TreeNode* tail;
while(!q.empty()){
TreeNode* t=q.front();
q.pop();
sum+=t->val;
cnt++;
if(t->left!=NULL){
q.push(t->left);
tail=t->left;
}
if(t->right!=NULL){
q.push(t->right);
tail=t->right;
}
if(t==last){
last=tail;
res.push_back(sum/cnt);
sum=cnt=0;
}
}
return res;
}
};
最新文章
- 1066: [SCOI2007]蜥蜴
- (翻译)《Hands-on Node.js》—— Why?
- rc.local文件
- Homework 1 -- The beginning
- 每日Scrum(9)
- mysql的binlog
- Selenium 进行web自动化测试
- 安卓在SQLiteOpenHelper类进行版本升级和降级
- linux 定时执行shell脚本
- phpstorm9整合本地apache和豆沙绿主题设置(附资源)
- 怎么给easyui中的datagrid加水平滚动条
- ES6使用fetch请求数据
- RabbitMQ在Ubuntu 16.04下的安装与配置
- 【转载】JAVA基础:注解
- 关于Redis的配置
- 无法清除cookie中的属性值之对解决问题的思考
- android开发学习——day7
- WPF快速实现XML可视化编辑工具
- [转载]C#委托与事件--简单笔记
- openssh-server
热门文章
- bryce1010专题训练——Splay树
- MYSQL5.7.11安装问题
- [转]Formatting the detail section to display multiple columns (水晶报表 rpt 一页多列)
- aspx页面调用webapi接口报错:远程服务器返回错误:(500)内部服务器错误
- .aspx设置跨域
- 面向对象-类-成员变量-局部变量-this
- ios 自定义消息提示框
- 自学Spring Boot
- OC 导入类 #import和@class 区别
- iOS的设计备忘录/资源集合(新手快速开发)