LeetCode637二叉樹的層平均值
阿新 • • 發佈:2020-07-30
題目連結
https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
題解
思路和層次遍歷(點選檢視)一樣,沒什麼區別。
// Problem: LeetCode 637 // URL: https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/ // Tags: Tree Queue // Difficulty: Easy #include <iostream> #include <queue> #include <vector> using namespace std; struct TreeNode{ int val; TreeNode* left; TreeNode* right; }; class Solution{ private: vector<double> result; double calcAverageOfLevel(vector<double>& vec){ double sum = 0; for (vector<double>::iterator it = vec.begin(); it!=vec.end(); ++it) sum += *it; return sum / vec.size(); } public: vector<double> averageOfLevels(TreeNode* root) { // 空樹,返回空陣列 if (root==nullptr) return this->result; // 父層節點,即當前正在遍歷的節點 queue<TreeNode*> parentNodes; parentNodes.push(root); // 遍歷父層節點的同時獲取下一層(子層)節點 while (!parentNodes.empty()){ // 子層結點,即下一層節點 queue<TreeNode*> childNodes; // 當前層的節點的值 vector<double> valOfLevel; // 遍歷當前層 while (!parentNodes.empty()){ root = parentNodes.front(); parentNodes.pop(); valOfLevel.push_back(root->val); if (root->left!=nullptr) childNodes.push(root->left); if (root->right!=nullptr) childNodes.push(root->right); } // 計算並存儲當前層節點值的平均值 this->result.push_back(this->calcAverageOfLevel(valOfLevel)); // 更新當前層 parentNodes = childNodes; } return this->result; } };
作者:@臭鹹魚
轉載請註明出處:https://www.cnblogs.com/chouxianyu/
歡迎討論和交流!