637-Average of Levels in Binary Tree

kevin聰發表於2018-04-25

Description

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

問題描述

給定二叉樹, 以陣列的形式返回其每層節點的平均值。(修改後返回值變成了List型別)


問題分析

通過深度遍歷來做, 關鍵是在遍歷的過程中利用好每個節點的depth


解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Integer> count = new ArrayList();
        List<Double> res = new ArrayList();

        average(root, 0, res, count);

        for(int i = 0; i < res.size();i++)  res.set(i, res.get(i) / count.get(i));

        return res;
    }
    public void average(TreeNode t, int i, List<Double> sum, List<Integer> count) {
        if (t == null)  return;

        if(i < sum.size()){
            sum.set(i, sum.get(i) + t.val);
            count.set(i, count.get(i) + 1);
        }else{
            sum.add(1.0 * t.val);
            count.add(1);
        }

        average(t.left, i + 1, sum, count);
        average(t.right, i + 1, sum, count);
    }
}

相關文章