[LeetCode] 637.Average of Levels in Binary Tree
来源:互联网 发布:mac os最新版本 编辑:程序博客网 时间:2024/06/07 01:21
[LeetCode] 637.Average of Levels in Binary Tree
- 题目描述
- 解题思路
- 实验代码
题目描述
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example:
Input:
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.
解题思路
题目意思很好理解,就是找到每一层结点的值的和的平均值。这道题关键的难点是怎么找到同一层的结点。我这里使用了vector和queue两个容器,利用其中的相关操作就能解决这个问题,具体过程见代码。
实验代码
/** * 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> v; queue<TreeNode*> q; q.push(root); while (!q.empty()) { long temp = 0; int s = q.size(); for (int i = 0; i < s; i++) { TreeNode* t = q.front(); q.pop(); if(t->left) q.push(t->left); if(t->right) q.push(t->right); temp += t->val; } v.push_back((double)temp/s); } return v; }};
阅读全文
0 0
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- LeetCode average Of Levels in Binary Tree
- Average of Levels in Binary Tree(leetcode)
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- 【LeetCode】637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode] 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- <leetcode>637. Average of Levels in Binary Tree
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode] 637.Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- vuex 概览
- Label propagation
- mybatis generator 自动生成代码模糊查询
- 个人记录:linux使用遇到的问题及解决方案 不定期总结
- vue之登录路由验证
- [LeetCode] 637.Average of Levels in Binary Tree
- Run Loops官方文档翻译(一)
- 安装 MySQL ODBC 驱动程序
- java获取文件路径
- HTTP 协议入门
- Qt Charts 模块的 C++ 类及描述
- 机器学习中的数学(1)-回归(regression)、梯度下降(gradient descent)
- SQLAlchemy使用学习
- 关于于渊的一个操作系统的实现第二版学习之第二章bochs裸机启动的练习