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;
}
};

最新文章

  1. 1066: [SCOI2007]蜥蜴
  2. (翻译)《Hands-on Node.js》—— Why?
  3. rc.local文件
  4. Homework 1 -- The beginning
  5. 每日Scrum(9)
  6. mysql的binlog
  7. Selenium 进行web自动化测试
  8. 安卓在SQLiteOpenHelper类进行版本升级和降级
  9. linux 定时执行shell脚本
  10. phpstorm9整合本地apache和豆沙绿主题设置(附资源)
  11. 怎么给easyui中的datagrid加水平滚动条
  12. ES6使用fetch请求数据
  13. RabbitMQ在Ubuntu 16.04下的安装与配置
  14. 【转载】JAVA基础:注解
  15. 关于Redis的配置
  16. 无法清除cookie中的属性值之对解决问题的思考
  17. android开发学习——day7
  18. WPF快速实现XML可视化编辑工具
  19. [转载]C#委托与事件--简单笔记
  20. openssh-server

热门文章

  1. bryce1010专题训练——Splay树
  2. MYSQL5.7.11安装问题
  3. [转]Formatting the detail section to display multiple columns (水晶报表 rpt 一页多列)
  4. aspx页面调用webapi接口报错:远程服务器返回错误:(500)内部服务器错误
  5. .aspx设置跨域
  6. 面向对象-类-成员变量-局部变量-this
  7. ios 自定义消息提示框
  8. 自学Spring Boot
  9. OC 导入类 #import和@class 区别
  10. iOS的设计备忘录/资源集合(新手快速开发)