美文网首页
637. Average of Levels in Binary

637. Average of Levels in Binary

作者: namelessEcho | 来源:发表于2017-09-11 17:31 被阅读0次

    Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
    树的BFS遍历 没啥好说的

    /**
     * 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) {
            ArrayList<Double> result =new ArrayList<>();
            ArrayDeque<TreeNode> queue = new ArrayDeque<>();
            if(root!=null)
            queue.add(root);
            else
            return result;
            while(!queue.isEmpty())
            {
                int count = queue.size();
                double sum = 0;
                for(int i = 0;i<count;i++)
                {
                    TreeNode node = queue.poll();
                    sum+=node.val;
                    if(node.left!=null)
                        queue.add(node.left);
                    if(node.right!=null)
                        queue.add(node.right);
                    
                }
                result.add(sum/count);
            }
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:637. Average of Levels in Binary

          本文链接:https://www.haomeiwen.com/subject/azpfsxtx.html