标签:struct tor push dfs self cto pop blog pen
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
标签:struct tor push dfs self cto pop blog pen
原文地址:http://www.cnblogs.com/xlqtlhx/p/7814236.html