|
| 1 | +/** |
| 2 | + * 1530. Number of Good Leaf Nodes Pairs |
| 3 | + * https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given the root of a binary tree and an integer distance. A pair of two different leaf |
| 7 | + * nodes of a binary tree is said to be good if the length of the shortest path between them is |
| 8 | + * less than or equal to distance. |
| 9 | + * |
| 10 | + * Return the number of good leaf node pairs in the tree. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * Definition for a binary tree node. |
| 15 | + * function TreeNode(val, left, right) { |
| 16 | + * this.val = (val===undefined ? 0 : val) |
| 17 | + * this.left = (left===undefined ? null : left) |
| 18 | + * this.right = (right===undefined ? null : right) |
| 19 | + * } |
| 20 | + */ |
| 21 | +/** |
| 22 | + * @param {TreeNode} root |
| 23 | + * @param {number} distance |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var countPairs = function(root, distance) { |
| 27 | + let result = 0; |
| 28 | + traverseTree(root); |
| 29 | + return result; |
| 30 | + |
| 31 | + function traverseTree(node) { |
| 32 | + if (!node) return []; |
| 33 | + if (!node.left && !node.right) return [1]; |
| 34 | + |
| 35 | + const leftDistances = traverseTree(node.left); |
| 36 | + const rightDistances = traverseTree(node.right); |
| 37 | + |
| 38 | + for (const left of leftDistances) { |
| 39 | + for (const right of rightDistances) { |
| 40 | + if (left + right <= distance) result++; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + const allDistances = []; |
| 45 | + for (const dist of leftDistances.concat(rightDistances)) { |
| 46 | + if (dist + 1 <= distance) allDistances.push(dist + 1); |
| 47 | + } |
| 48 | + |
| 49 | + return allDistances; |
| 50 | + } |
| 51 | +}; |
0 commit comments