>>문제설명
leetcode.com/problems/average-of-levels-in-binary-tree/
Average of Levels in Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
>mySolution
class Solution {
public double getAverage(LinkedList<TreeNode> linkedList){
long sum = 0;
for(TreeNode treeNode : linkedList){
sum += treeNode.val;
}
return (double)sum / linkedList.size();
}
public List<Double> averageOfLevels(TreeNode root) {
LinkedList<TreeNode> linkedList = new LinkedList<>();
LinkedList<TreeNode> nextList = new LinkedList<>();
List<Double> answerList = new ArrayList<>();
linkedList.add(root);
while (!linkedList.isEmpty()){
answerList.add(getAverage(linkedList));
nextList.clear();
while (!linkedList.isEmpty()){
TreeNode treeNode = linkedList.poll();
if(treeNode.left != null) nextList.add(treeNode.left);
if(treeNode.right != null) nextList.add(treeNode.right);
}
linkedList.addAll(nextList);
}
return answerList;
}
}
> Result
> Modify
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
LinkedList<TreeNode> linkedList = new LinkedList<>();
List<Double> answerList = new ArrayList<>();
linkedList.add(root);
long sum;
int size;
while (!linkedList.isEmpty()){
sum = 0;
size = linkedList.size();
for(int idx = 0; idx < size; idx++){
TreeNode treeNode = linkedList.poll();
sum += treeNode.val;
if(treeNode.left != null) linkedList.addLast(treeNode.left);
if(treeNode.right != null) linkedList.addLast(treeNode.right);
}
answerList.add((double)sum / size);
}
return answerList;
}
}
>Result
leetCode 엔진 자체가 같은 코드를 넣어도 결과가 다르게 나온다는 점을 알았다.
728x90
반응형
'Algorithms > LeetCode DailyChallenge' 카테고리의 다른 글
[LeetCode] 1721. Swapping Nodes in a Linked List / JAVA (0) | 2021.03.14 |
---|---|
[LeetCode] 322. Coin Change / JAVA (0) | 2021.03.12 |
[LeetCode] 12. Integer to Roman / JAVA (0) | 2021.03.10 |
[LeetCode] 1332. Remove Palindromic Subsequences (0) | 2021.03.08 |
[LeetCode] Short Encoding of Words (0) | 2021.03.06 |