1. 문제 분석
문제분석
--------------------
이진트리의 root가 주어질 때, 트리 속 노드의 갯수를 반환하라.
O(n) 시간복잡도 미만으로 풀어라.
제한조건
--------------------
- 트리 속의 노드 갯수는 0 ~ 5*10^4이다.
- 0 <= Node.val <= 5 * 10^4
2. 접근 방법
접근방법
--------------------
재귀함수로 left, right를 방문하여 node가 존재하면 외부 변수 count를 추가한다.
3. 코드
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
var countNodes = function(root) {
if (!root) {
return 0;
}
let count = 0;
function helper(node) {
if (!node) {
return null;
}
count++;
helper(node.left);
helper(node.right);
}
helper(root);
return count;
};
4. 복잡도 분석
- 시간복잡도: O(n)
- 공간복잡도: O(1)
root 노드의 왼쪽, 오른쪽 노드를 재귀함수로 호출하면서 자식 노드가 존재하면 외부 변수 count에 값을 추가하여 갯수를 반환한다.
'Leetcode' 카테고리의 다른 글
[Leetcode] 199. Binary Tree Right Side View - JS (0) | 2024.11.26 |
---|---|
[Leetcode] 236. Lowest Common Ancestor of a Binary Tree - JS (0) | 2024.11.25 |
[Leetcode] 173. Binary Search Tree Iterator - JS (0) | 2024.11.23 |
[Leetcode] 124. Binary Tree Maximum Path Sum - JS (0) | 2024.11.22 |
[Leetcode] 129. Sum Root to Leaf Numbers - JS (0) | 2024.11.21 |