leetcode Add to List 637. Average of Levels in Binary Tree
来源:互联网 发布:csgo 知乎 编辑:程序博客网 时间:2024/06/03 13:33
就是对二叉树每一层求平均值。
开始想法用层次遍历,然而又不知道该点是在哪一层。
所以要求没一点的深度,而通过先序遍历递归求没一点的深度的过程中。
好像并不需要再去层次遍历,结果就已经很明显了。
要注意leetcode的树要用->。
两个数组用来存结果。
没有数据量范围我就写的100000.
还要注意有一个奇葩数据
2147483647 两个节点也是2147483647 ,所以要改成long long
/** * 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: long long a[100000]; int b[100000]; void f(TreeNode* root,int d) { if(root!=NULL){ a[d]+=root->val; b[d]+=1; //cout<<d<<"-"<<root->val<<" "; f(root->left,++d); --d; f(root->right,++d); } } vector<double> averageOfLevels(TreeNode* root) { memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); f(root,0); vector<double> ans; for(int i=0;i<100000;i++){ if(b[i]!=0) ans.push_back((double)a[i]/(double)b[i]); } return ans; }};
阅读全文
0 0
- 【LeetCode】Add to List 637. Average of Levels in Binary Tree
- leetcode Add to List 637. Average of Levels in Binary Tree
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- LeetCode average Of Levels in Binary Tree
- Average of Levels in Binary Tree(leetcode)
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- 【LeetCode】637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode] 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- <leetcode>637. Average of Levels in Binary Tree
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode] 637.Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- python笔记(二)一些特别语法
- CSS-派生选择器
- CODER-动态规划编程题
- 双色Hanoi塔问题
- Twincat3
- leetcode Add to List 637. Average of Levels in Binary Tree
- C++动态规划算法之0-1背包问题
- 欢迎使用CSDN-markdown编辑器
- python笔记(三)函数的参数
- Android的工厂模式
- 电子书收藏
- cJSON的模拟实现
- linux 笔记(五)(Shell基础)
- 《程序员》2014年11月刊:电商峰值系统架构设计