【C++】返回每一層二叉樹的平均值(層序遍歷)

wshidaboss發表於2024-03-06
//返回每一層二叉樹的平均值(廣度優先搜尋,佇列) 層序遍歷
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;
}

相關文章