LeetCode 637. 二叉树的层平均值
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出:[3, 14.5, 11]
解释:
第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。
提示:
节点值的范围在32位有符号整数范围内。
思路:
这一题,难度倒是不难,就是才接触LeetCode的OJ没几天,不太熟悉他的风格,搞得头有点大= =
问题出在全局变量上,因为后端的判题机制是多次运行main函数这一点不清楚,所以我只在开头初始化了一下,结果就导致我自己执行代码是对的,一送到后端判题机就错了,找了半天还不知道问题在哪(┙>∧<)┙へ┻┻
解决方法当然就是,在main函数里进行初始化就OK啦~
关于这题的解题方法,其实有很多,不同的遍历方法都可以,看个人喜好~我用滴是先序(代码少写起来快~)
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 int counts[1010]={0}; 11 double value[1010]={0}; 12 int max_depth=0; 13 void preorder(TreeNode * root,int depth) 14 { 15 if(root==NULL) 16 return; 17 max_depth=depth>max_depth?depth:max_depth; 18 counts[depth]++; 19 value[depth]+=root->val; 20 preorder(root->left,depth+1); 21 preorder(root->right,depth+1); 22 } 23 class Solution { 24 public: 25 vector<double> averageOfLevels(TreeNode* root) { 26 vector<double> answer; 27 memset(counts,0,sizeof(counts)); 28 memset(value,0,sizeof(value)); 29 max_depth=0; 30 preorder(root,0); 31 for(int i=0;i<=max_depth;++i) 32 { 33 answer.push_back(value[i]/counts[i]); 34 } 35 return answer; 36 } 37 };

浙公网安备 33010602011771号