您的位置:首页 > 编程语言 > Java开发

LeetCode 637 : Average of Levels in Binary Tree(java)

2017-07-19 23:54 489 查看
原题:

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input:
3
/ \
9  20
/  \
15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].


Explanation:

The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

The range of node’s value is in the range of 32-bit signed integer.

思路:求二叉树每一层的平均值。用leafNumList存储每一层叶子节点个数,用deepList存储每一层的平均值。

代码:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void calculation(TreeNode root,int deep,List<Double> deepList,List<Integer> leafNumList){
if(root!=null){
if(deepList.size()<deep){
deepList.add(1.0*root.val);
leafNumList.add(1);
}else{
deepList.set(deep-1,(deepList.get(deep-1)*leafNumList.get(deep-1)+root.val)/(leafNumList.get(deep-1)+1));
leafNumList.set(deep-1,leafNumList.get(deep-1)+1);
}
calculation(root.left,deep+1,deepList,leafNumList);
calculation(root.right,deep+1,deepList,leafNumList);
}
}
public List<Double> averageOfLevels(TreeNode root) {
//deepList存储每一层的平均值
List<Double> deepList= new ArrayList<>();
//leafNumList存储每一层叶子节点个数
List<Integer> leafNumList= new ArrayList<>();
calculation(root,1,deepList,leafNumList);
return deepList;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java 二叉树