Skip to content

Commit

Permalink
Leetcode 1530
Browse files Browse the repository at this point in the history
  • Loading branch information
herrera-ignacio committed Jul 18, 2024
1 parent c7a2391 commit 380dce8
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@
- [1323: Maximum 69 number](problems/leetcode/1323)
- [1356: Sort integers by the number of bits with value 1](problems/leetcode/1356)
- [1509: Minimum difference between largest and smallest value in three moves](problems/leetcode/1509)
- [1530: NUmber of Good Leaf Nodes Pairs](problems/leetcode/1530)
- [1544: Make the string great](problems/leetcode/1544)
- [1704: Determine if string halves are alike](problems/leetcode/1704)
- [1706: Where will the ball fall](problems/leetcode/1706)
Expand Down
51 changes: 51 additions & 0 deletions problems/leetcode/1530/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/
// solution based on https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/solutions/5493798/ultimate-1-ms-solution-beats-100-java-c-py-js-go-beginner-friendly-explanation/
/**
* 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}
*/
const countPairs = function(root, distance) {
let count = 0;
const MAX_DISTANCE = 10;

function dfs(node) {
if (!node) return new Array(MAX_DISTANCE + 1).fill(0);

if (!node.left && !node.right) {
// leaf
const res = new Array(MAX_DISTANCE + 1).fill(0);
res[1] = 1;
return res;
}

const left = dfs(node.left);
const right = dfs(node.right);

for (let i = 1; i <= distance; i++) {
for (let j = 1; j <= distance - i; j++) {
// only leafs will have non-zero values
count += left[i] * right[j];
}
}

const res = new Array(MAX_DISTANCE + 1).fill(0);
for (let i = 1; i < MAX_DISTANCE; i++) {
res[i + 1] = left[i] + right[i];
}

return res;
}

dfs(root);

return count;
};

0 comments on commit 380dce8

Please sign in to comment.