637. 二叉樹的層平均值

解題思路

層次遍歷

代碼

class Solution {
public:
	vector<double> averageOfLevels(TreeNode* root) {
		vector<double> res;
		queue<TreeNode* >q;
		if (root!=NULL)
		{
			q.push(root);
			while (!q.empty())
			{
				double s = 0.0;
				int qSize = q.size();
				for (int i=0;i<qSize;i++)
				{
					TreeNode* front = q.front();
					s += front->val;
					q.pop();
					if (front->left != NULL) q.push(front->left);
					if (front->right != NULL) q.push(front->right);
				}
				res.push_back(s / qSize);
			}
		}
		return res;
	}
};
發佈了111 篇原創文章 · 獲贊 19 · 訪問量 8307
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章