本文主要是介绍Average of Levels in Binary Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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].
思路:就是一个level order traverse;
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public List<Double> averageOfLevels(TreeNode root) {List<Double> list = new ArrayList<Double>();if(root == null) {return list;}Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.offer(root);while(!queue.isEmpty()) {int size = queue.size();int levelsize = size;double cursum = 0.0;while(size > 0) {TreeNode node = queue.poll();size--;cursum += node.val;if(node.left != null) {queue.offer(node.left);}if(node.right != null) {queue.offer(node.right);}}list.add(cursum / levelsize);}return list;}
}
这篇关于Average of Levels in Binary Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!