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]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ queue=[] res=[] queue.append(root) while(len(queue)!=0): num=len(queue) sum=0 for i in range(num): temp=queue[0] sum+=temp.val del queue[0] if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) avg=sum/float(num) res.append(avg) return res