leetcode.637 二叉树的层平均值(java实现)

  • 问题描述

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].

  • 解决方案

通过加null来进行层的隔离,注意边界条件即可。

/**
 * 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> result = new ArrayList<>();
        double sum = 0;
        int size = 0;
        LinkedList<TreeNode> list = new LinkedList<TreeNode>();
        list.add(root);
        list.add(null);
        while(!list.isEmpty()){
     
            TreeNode cur = list.pollFirst();
            if(cur == null){
     
                result.add(sum / size);
                sum = 0;
                size = 0;
                if(!list.isEmpty())
                    list.add(null);
            }
            else if(cur != null){
     
                size ++;
                sum += cur.val;
                if(cur.left != null)
                list.add(cur.left);
                if(cur.right != null)
                list.add(cur.right);
                
            }
        }
        return result;
    }
}

你可能感兴趣的:(#,二叉树,Leetcode,算法题目)