From a7f924c47cd278760f03df902124f48033af5c5c Mon Sep 17 00:00:00 2001 From: yuvaraja99 <91772765+yuvaraja99@users.noreply.github.com> Date: Sat, 29 Oct 2022 00:31:07 +0530 Subject: [PATCH] Created code average-of-levels-in-binary-tree.cpp Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. --- code average-of-levels-in-binary-tree.cpp | 36 +++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 code average-of-levels-in-binary-tree.cpp diff --git a/code average-of-levels-in-binary-tree.cpp b/code average-of-levels-in-binary-tree.cpp new file mode 100644 index 0000000..0e48dba --- /dev/null +++ b/code average-of-levels-in-binary-tree.cpp @@ -0,0 +1,36 @@ +/* +Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. +*/ + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} + }; + +class Solution { +public: + vector averageOfLevels(TreeNode* root) { + vector result; + vector q; + q.emplace_back(root); + while (!q.empty()) { + long long sum = 0, count = 0; + vector next_q; + for (const auto& n : q) { + sum += n->val; + ++count; + if (n->left) { + next_q.emplace_back(n->left); + } + if (n->right) { + next_q.emplace_back(n->right); + } + } + swap(q, next_q); + result.emplace_back(sum * 1.0 / count); + } + return result; + } +};