leetCode_637_AverageOfLevelsInBinaryTree
2017-10-09 15:11
447 查看
题目描述
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array./** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.Queue; class Solution { public List<Double> averageOfLevels(TreeNode root) { if (root == null) return null; List<Double> list = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); list.add((double)root.val); queue.add(root); TreeNode last = root; TreeNode nextLast = root; double averageSum = 0; int count = 0; while (queue.size() != 0) { TreeNode temp = queue.poll(); if (temp.left != null) { nextLast = temp.left; queue.add(temp.left); averageSum += temp.left.val; count ++; } if (temp.right != null) { nextLast = temp.right; queue.add(temp.right); averageSum += temp.right.val; count ++; } if (temp == last) { if (nextLast != last) { list.add(averageSum / count); averageSum = 0; count = 0; last = nextLast; } } } return list; } }
相关文章推荐
- 【LeetCode】637 Average of Levels in Binary Tree
- LeetCode 637 Average of Levels in Binary Tree(二叉树层序遍历)
- LeetCode 637 : Average of Levels in Binary Tree(java)
- LeetCode 637: Average of Levels in Binary Tree
- 【LeetCode】637 Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- LeetCode Average of Levels in Binary Tree
- LeetCode average Of Levels in Binary Tree
- [LeetCode] Average of Levels in Binary Tree 二叉树的层平均值
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- leetcode[Average of Levels in Binary Tree]//待整理多种解法
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- leetcode编程记录13 #637 Average of Levels in Binary Tree
- leetcode Average of Levels in Binary Tree 二叉树每层的平均值
- LeetCode Weekly Contest 40(1) - Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- Average of Levels in Binary Tree(leetcode)
- Average of Levels in Binary Tree问题及解法