• 문제 링크
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
• 풀이 코드
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list = new ArrayList<>();
Deque<TreeNode> dq = new ArrayDeque<>();
dq.offer(root);
while (!dq.isEmpty()) {
int size = dq.size();
long sum = 0;
for (int i = 0; i < size; i++) {
TreeNode node = dq.removeFirst();
sum += node.val;
if (node.left != null) dq.offer(node.left);
if (node.right != null) dq.offer(node.right);
}
list.add(sum * 1.0 / size);
}
return list;
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 645. Set Mismatch - Java (0) | 2026.09.16 |
|---|---|
| [LeetCode] 643. Maximum Average Subarray I - Java (0) | 2026.09.15 |
| [LeetCode] 628. Maximum Product of Three Numbers - Java (0) | 2026.09.13 |
| [LeetCode] 617. Merge Two Binary Trees - Java (0) | 2026.09.12 |
| [LeetCode] 605. Can Place Flowers - Java (0) | 2026.09.11 |
댓글