二叉树的层平均值
计算每一行的总数,然后求均值。转换double
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<double> averageOfLevels(TreeNode* root) { vector<double> result; TreeNode* node ; queue<TreeNode*> my_que; if(root == nullptr) return result; else { my_que.push(root); } while(my_que.empty() != 1) { int size = my_que.size(); double sum = 0; for(int i=0 ; i<size ; i++) { node = my_que.front(); my_que.pop(); sum = sum + (double)node->val; if(node->left != nullptr) my_que.push(node->left); if(node->right != nullptr) my_que.push(node->right); } result.push_back(sum/size); } return result; } };