//返回每一层二叉树的平均值(广度优先搜索,队列) 层序遍历
vector<double> averageOfLevels(TreeNode* root) {
  vector<double> ans;
  if (!root) return ans;
  queue<TreeNode*> q;
  q.push(root);
  while (!q.empty()) {
    int count = q.size();
    double sum = 0;
    for (int i = 0; i < count; ++i) {
      TreeNode* node = q.front();
      q.pop();
      sum += node->val;
      if (node->left) q.push(node->left);
      if (node->right) q.push(node->right);
    }
    ans.push_back(sum / count);
  }
  return ans;
}

 

posted on 2024-03-06 11:35  wshidaboss  阅读(7)  评论(0编辑  收藏  举报