알고리즘/탐색

[LeetCode] 637. Average of Levels in Binary Tree - Java

jny0 2023. 9. 8. 02:14
 

Average of Levels in Binary Tree - LeetCode

Can you solve this real interview question? Average of Levels in Binary Tree - Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.   Examp

leetcode.com

 

문제

더보기

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
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].

Example 2:

Input: root = [3,9,20,15,7]
Output: [3.00000,14.50000,11.00000]

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1

 

이진트리의 root가 주어졌을 때, 트리의 각 레벨의 노드 값의 평균을 구하는 문제이다.

 


 

내 풀이

 

BFS 사용

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> answer = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);

        while(!queue.isEmpty()){
            int size = queue.size();
            long sum = 0;

            for(int i=0; i<size; i++){
                TreeNode node = queue.poll();
                sum += node.val;

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }

            }
            answer.add((double)sum/size);
        }   

        return answer;
    }
}

BFS를 사용해서 트리를 탐색하고, 각 레벨의 평균을 계산하면 된다.

  • 시간복잡도 : O(N) - 모든 노트 탐색
  • 공간복잡도 : O(W) - 트리의 가장 넓은 레벨의 노드의 개수에 비례