Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 개발자취업
- TiL
- 중간이들
- redis
- 유노코딩
- JavaScript
- 파이썬프로그래밍기초
- 방송대
- 파이썬
- SQL
- 프로그래머스
- 코드잇
- Git
- MySQL
- nestjs
- Python
- HTML
- 데이터베이스시스템
- 자격증
- 방송대컴퓨터과학과
- CSS
- 코딩테스트
- node.js
- 엘리스sw트랙
- 99클럽
- Cookie
- 꿀단집
- aws
- 코딩테스트준비
- 항해99
Archives
- Today
- Total
배꼽파지 않도록 잘 개발해요
99클럽 코테 스터디 31일차 TIL - Number of Good Leaf Nodes Pairs 본문
/**
* 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)
* }
*/
/**
* @param {TreeNode} root
* @param {number} distance
* @return {number}
*/
var countPairs = function(root, distance) {
let result = 0;
function dfs(node) {
if (!node) return new Map();
// Leaf node
if (!node.left && !node.right) {
let map = new Map();
map.set(1, 1); // Depth 1 with 1 count
return map;
}
// Recursive DFS to get leaf counts from left and right subtrees
const leftCounts = dfs(node.left);
const rightCounts = dfs(node.right);
// Count good pairs between leaf nodes in left and right subtrees
for (let [lDepth, lCount] of leftCounts) {
for (let [rDepth, rCount] of rightCounts) {
if (lDepth + rDepth <= distance) {
result += lCount * rCount;
}
}
}
// Prepare the count map for the current node
let currentCounts = new Map();
for (let [depth, count] of leftCounts) {
if (depth + 1 <= distance) {
currentCounts.set(depth + 1, (currentCounts.get(depth + 1) || 0) + count);
}
}
for (let [depth, count] of rightCounts) {
if (depth + 1 <= distance) {
currentCounts.set(depth + 1, (currentCounts.get(depth + 1) || 0) + count);
}
}
return currentCounts;
}
dfs(root);
return result;
}
728x90
'코딩테스트 > 99클럽' 카테고리의 다른 글
99클럽 코테 스터디 31일차 TIL - 영역 구하기 (0) | 2024.08.26 |
---|---|
99클럽 코테 스터디 31일차 TIL - 양 한마리 (0) | 2024.08.24 |
99클럽 코테 스터디 31일차 TIL - Bad Grass (0) | 2024.08.23 |
99클럽 코테 스터디 31일차 TIL - Clear Cold Water (0) | 2024.08.22 |
99클럽 코테 스터디 29일차 TIL - Arranging Coins (0) | 2024.08.21 |