[230824] Leetcode - 637, JS function
Leetcode - 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 재귀함수 사용해서 풀었음
/**
* @param {TreeNode} root
* @return {number[]}
*/
var averageOfLevels = function (root) {
const result = [];
const nodeCount = [];
const bfs = (root, level) => {
if (result[level] === undefined) {
result[level] = 0;
nodeCount[level] = 0;
}
result[level] += root.val;
nodeCount[level] += 1;
if (root.left) bfs(root.left, level + 1);
if (root.right) bfs(root.right, level + 1);
};
bfs(root, 0);
for (i = 0; i < result.length; i++) {
result[i] = result[i] / nodeCount[i];
}
return result;
};
- queue로 푼 방식
- leetcode 는 큐 라이브러리를 제공함
const averageOfLevels = (root) => { const result = []; const queue = new Queue([root]); while (queue.size()) { let sum = 0; let levelSize = queue.size(); for (let i = 0; i < levelSize; i++) { const node = queue.dequeue(); sum += node.val; if (node.left) { queue.enqueue(node.left); } if (node.right) { queue.enqueue(node.right); } } result.push(sum / levelSize); } return result; };
JS 화살표, 일반함수 arguments 객체 차이점
1. 일반 함수의 arguments
객체
function showArguments() {
for (let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
showArguments(1, 2, 3, 4); // 1, 2, 3, 4 순서대로 출력됩니다.
arguments
객체를 통해 전달된 모든 인자 참조할 수 있음
2. 화살표 함수의 arguments
객체
function outerFunction() {
const innerArrowFunction = () => {
console.log(arguments[0]);
}
innerArrowFunction();
}
outerFunction('안녕하세요'); // "안녕하세요"가 출력됩니다.
- 화살표함수는 자체적인
arguments
객체를 가지지 않음 - 만약 화살표 함수 내에서
arguments
참조하려고 하면 상위 스코프의arguments
객체를 참조함
JS 화살표, 일반함수 this 바인딩 차이점
1. 일반 함수 경우
- 해당 메서드를 호출하는 객체를 참조
- 서브 클래스에서 슈퍼 클래스를 오버라이드하면 내부에서
super
를 써서 슈퍼 클래스의 메서드를 호출할때도this
는 현재 객체(서브 클래스) 인스턴스를 참고함
2. 화살표 함수
- 화살표함수는 자체적인
this
바인딩을 가지지 않음 - 화살표 함수가 정의된 스코프의
this
를 참조
예시
class SuperClass {
constructor() {
this.name = "슈퍼 클래스";
}
normalMethod() {
console.log(`일반 함수: ${this.name}`);
}
arrowMethod = () => {
console.log(`화살표 함수: ${this.name}`);
}
}
class SubClass extends SuperClass {
constructor() {
super();
this.name = "서브 클래스";
}
testMethods() {
this.normalMethod();
this.arrowMethod();
}
}
const obj = new SubClass();
obj.testMethods();
// 결과:
// 일반 함수: 서브 클래스
// 화살표 함수: 슈퍼 클래스
Leave a comment