[LeetCode] Average of Levels in Binary Tree 二叉樹的層平均值
阿新 • • 發佈:2018-12-27
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
- The range of node's value is in the range of 32-bit signed integer.
這道題讓我們求一個二叉樹每層的平均值,那麼一看就是要進行層序遍歷了,直接上queue啊,如果熟悉層序遍歷的方法,那麼這題就沒有什麼難度了,直接將每層的值累計加起來,除以該層的結點個數,存入結果res中即可,參見程式碼如下:
解法一:
class Solution { public: vector<double> averageOfLevels(TreeNode* root) {if (!root) return {}; vector<double> res; queue<TreeNode*> q{{root}}; while (!q.empty()) { int n = q.size(); double sum = 0; for (int i = 0; i < n; ++i) { TreeNode *t = q.front(); q.pop(); sum+= t->val; if (t->left) q.push(t->left); if (t->right) q.push(t->right); } res.push_back(sum / n); } return res; } };
下面這種方法雖然是利用的遞迴形式的先序遍歷,但是其根據判斷當前層數level跟結果res中已經初始化的層數之間的關係對比,能把當前結點值累計到正確的位置,而且該層的結點數也自增1,這樣我們分別求了兩個陣列,一個數組儲存了每行的所有結點值,另一個儲存了每行結點的個數,這樣對應位相除就是我們要求的結果了,參見程式碼如下:
解法二:
class Solution { public: vector<double> averageOfLevels(TreeNode* root) { vector<double> res, cnt; helper(root, 0, cnt, res); for (int i = 0; i < res.size(); ++i) { res[i] /= cnt[i]; } return res; } void helper(TreeNode* node, int level, vector<double>& cnt, vector<double>& res) { if (!node) return; if (res.size() <= level) { res.push_back(0); cnt.push_back(0); } res[level] += node->val; ++cnt[level]; helper(node->left, level + 1, cnt, res); helper(node->right, level + 1, cnt, res); } };
類似題目:
參考資料: