From 380dce8cbb7f572dc0a2ca89bd22e847f8ff30d7 Mon Sep 17 00:00:00 2001 From: Ignacio Herrera Date: Thu, 18 Jul 2024 20:01:14 -0300 Subject: [PATCH] Leetcode 1530 --- README.md | 1 + problems/leetcode/1530/solution.js | 51 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 problems/leetcode/1530/solution.js diff --git a/README.md b/README.md index b593f1b..599913d 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/problems/leetcode/1530/solution.js b/problems/leetcode/1530/solution.js new file mode 100644 index 0000000..88f86c8 --- /dev/null +++ b/problems/leetcode/1530/solution.js @@ -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; +};