[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;
}
};
本文介绍了一种求解二叉树各层节点平均值的方法。通过使用队列实现层次遍历,计算每一层节点值的总和并求平均。
398

被折叠的 条评论
为什么被折叠?



