Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
题意:求二叉树相同层节点的平均值。
思路:广度优先遍历
/**
* 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> ans;
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;
}
ans.push_back((double)temp/s);
}
return ans;
}
};
用一个队列维持在同一层的所有节点。