计算二叉树每层平均值
2017-08-30 23:19
190 查看
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 1:
按照题目要求求解二叉树每层的平均值,既然按照层级求解,那么可以说是层次遍历或者说是BFS的典型问题。
关键在于如何正确的在遍历过程中分层,思路是根据压入队列的元素个数划分。代码如下:
/**
* 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;
if (root == NULL)
return v;
queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
int num = q.size();
long temp = 0;
for (int i = 0; i < num; i++)
{
TreeNode *top = q.front();
q.pop();
if (top->left != NULL)
q.push(top->left);
if (top->right != NULL)
q.push(top->right);
temp += top->val;
}
v.push_back((double)temp / num);
}
return v;
}
};
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
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].
按照题目要求求解二叉树每层的平均值,既然按照层级求解,那么可以说是层次遍历或者说是BFS的典型问题。
关键在于如何正确的在遍历过程中分层,思路是根据压入队列的元素个数划分。代码如下:
/**
* 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;
if (root == NULL)
return v;
queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
int num = q.size();
long temp = 0;
for (int i = 0; i < num; i++)
{
TreeNode *top = q.front();
q.pop();
if (top->left != NULL)
q.push(top->left);
if (top->right != NULL)
q.push(top->right);
temp += top->val;
}
v.push_back((double)temp / num);
}
return v;
}
};
相关文章推荐
- Leetcode637. BFS计算二叉树每层节点的平均值
- Leetcode637. BFS计算二叉树每层节点的平均值
- 二叉树宽度的计算
- 第十周项目--【计算二叉树节点个数】
- 计算二叉树的高度中序迭代版本,有错误待定位
- Linux-C基础知识学习:C语言作业-将5个学生成绩保存在一个数组中,单独实现一个计算平均成绩的average函数, 在main函数中获取该函数返回的平均值,并打印。
- 二叉树----宽度计算
- java计算二叉树的高度以及叶节点个数
- 二叉树计算算式(各种遍历)
- MapReduce功能实现七---小综合(多个job串行处理计算平均值)
- Python基础(6)——实现输入任意多个数,并计算其平均值
- C++计算二叉树的节点数和高度
- 小代码 二叉树非递归与结点计算
- 计算二叉树深度
- 第10周项目3-利用二叉树遍历思想解决问题(1)计算二叉树节点个数
- C语言中计算二叉树的宽度的两种方式
- 计算二叉树的高度、节点数、叶子节点数
- 假设二叉树采用链接方式存储,编写一个计算一颗二叉树t的高度的函数
- 有关二叉树的计算题和知识
- 以二叉链表为存储结构, 试编写计算二叉树中叶子结点数目的递归算法.