Average of Levels in Binary Tree
Posted PirateLHX
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Average of Levels in Binary Tree相关的知识,希望对你有一定的参考价值。
C++:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<double> averageOfLevels(TreeNode* root) { vector<double> res; queue<TreeNode*> q; q.push(root); double sum,avg; while(!q.empty()) { int num=q.size(); sum=0; for(int i=0;i<num;i++) { TreeNode* temp=q.front(); sum+=temp->val; q.pop(); if(temp->left!=NULL) q.push(temp->left); if(temp->right!=NULL) q.push(temp->right); } avg=sum/num; res.push_back(avg); } return res; } };
def averageOfLevels(self, root): info = [] def dfs(node, depth = 0): if node: if len(info) <= depth: info.append([0, 0]) info[depth][0] += node.val info[depth][1] += 1 dfs(node.left, depth + 1) dfs(node.right, depth + 1) dfs(root) return [s/float(c) for s, c in info]
以上是关于Average of Levels in Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
637. Average of Levels in Binary Tree
637. Average of Levels in Binary Tree
637. Average of Levels in Binary Tree
637. Average of Levels in Binary Tree