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
- Cookie
- 프로그래머스
- 엘리스sw트랙
- redis
- 유노코딩
- 파이썬프로그래밍기초
- CSS
- 파이썬
- 방송대
- TiL
- 방송대컴퓨터과학과
- 클라우드컴퓨팅
- aws
- 꿀단집
- 코딩테스트준비
- mongoDB
- 데이터베이스시스템
- 중간이들
- Git
- Python
- 99클럽
- 오픈소스기반데이터분석
- nestjs
- node.js
- HTML
- 코딩테스트
- JavaScript
- 항해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 |