Average of Levels in Binary Tree
2017-10-08 21:59
417 查看
题意:求每一层的数据平均值,放到Vector里
思路:层序遍历,没啥难的
/**
* 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()){
int num = q.size();
double sum = 0;
for(int i = 0;i<num ;i++){
TreeNode* temp = q.front();
q.pop();
sum += temp->val;
if(temp->left!=NULL){
q.push(temp->left);
}
if(temp->right!=NULL){
q.push(temp->right);
}
}
v.push_back(sum/num);
}
return v;
}
};
思路:层序遍历,没啥难的
/**
* 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()){
int num = q.size();
double sum = 0;
for(int i = 0;i<num ;i++){
TreeNode* temp = q.front();
q.pop();
sum += temp->val;
if(temp->left!=NULL){
q.push(temp->left);
}
if(temp->right!=NULL){
q.push(temp->right);
}
}
v.push_back(sum/num);
}
return v;
}
};
相关文章推荐
- 【LeetCode】637 Average of Levels in Binary Tree
- leetCode_637_AverageOfLevelsInBinaryTree
- leetcode编程记录13 #637 Average of Levels in Binary Tree
- LeetCode 637: Average of Levels in Binary Tree
- Average of Levels in Binary Tree
- leetcode[Average of Levels in Binary Tree]//待整理多种解法
- 637. Average of Levels in Binary Tree
- LeetCode 637 Average of Levels in Binary Tree(二叉树层序遍历)
- LC-Average of Levels in Binary Tree
- LeetCode Weekly Contest 40(1) - Average of Levels in Binary Tree
- Average of Levels in Binary Tree(leetcode)
- 27.leetCode637:Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- Average of Levels in Binary Tree
- Average of Levels in Binary Tree
- LeetCode Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- leetcode Average of Levels in Binary Tree 二叉树每层的平均值
- Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree