0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LeetCode: Average of Levels in Binary Tree

Posted at

Introduction

Treeの問題。各レベルにおける平均値を求めよ、というお題です。
https://leetcode.com/problems/average-of-levels-in-binary-tree/description/

Problem statement

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].
Note:
The range of node's value is in the range of 32-bit signed integer.

My solution

Easyレベルだったので単純かなと思ったのですが、長々としたSolutionになりました。

方針:

  1. Mapにて各レベルにおけるノードの値の合計値とその数を記録
    sumByLevel:ノードの値の合計値
    countByLevel:ノードの個数
  2. TreeNodeに加えてレベルの情報もQueueに組みこむ

引っかかったポイント:

  1. sumByLevelにてvalueにIntegerを使うと、テストケースが通らないケースあり
    そのため、 Map sumByLevel と定義
  2. integer -> double の変換を考慮しておらず、コンパイルエラーが発生

Time Complexity = O(N): すべてのTreeを走査する必要があるため
Space Complexity = O(h): マップを使い、各レベルの情報を記憶しているため

/**
 * 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<>();
        if (root == null) {
            return list;
        }
        Map<Integer, Integer> countByLevel = new HashMap<>();
        Map<Integer, Long> sumByLevel = new HashMap<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        Queue<Integer> height = new ArrayDeque<>();
        queue.add(root);
        height.add(1);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            int curHeight = height.poll();
            if (countByLevel.containsKey(curHeight)) {
                countByLevel.put(curHeight, countByLevel.get(curHeight) + 1);
            } else {
                countByLevel.put(curHeight, 1);
            }
            if (sumByLevel.containsKey(curHeight)) {
                sumByLevel.put(curHeight, (long) sumByLevel.get(curHeight) + cur.val);
            } else {
                sumByLevel.put(curHeight, (long) cur.val);
            }
            if (cur.left != null) {
                queue.add(cur.left);
                height.add(curHeight + 1);
            }
            if (cur.right != null) {
                queue.add(cur.right);
                height.add(curHeight + 1);                
            }            
        }
        for (Integer key: sumByLevel.keySet()) {
            list.add((double) sumByLevel.get(key) / countByLevel.get(key));
        }
        return list;
    }
}

Optimal solution

この問題の解説によると、より良い回答があるそうです。
https://leetcode.com/articles/average-of-levels/
ただ、上記回答もTimeComplexity = O(N)、Space Complexity = O(h) のため、私の回答と変わらないので良いかな?と思ってみたり。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?