|
| 1 | +/** |
| 2 | + * 1719. Number Of Ways To Reconstruct A Tree |
| 3 | + * https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array pairs, where pairs[i] = [xi, yi], and: |
| 7 | + * - There are no duplicates. |
| 8 | + * - xi < yi |
| 9 | + * |
| 10 | + * Let ways be the number of rooted trees that satisfy the following conditions: |
| 11 | + * - The tree consists of nodes whose values appeared in pairs. |
| 12 | + * - A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is |
| 13 | + * an ancestor of xi. |
| 14 | + * - Note: the tree does not have to be a binary tree. |
| 15 | + * |
| 16 | + * Two ways are considered to be different if there is at least one node that has different |
| 17 | + * parents in both ways. |
| 18 | + * |
| 19 | + * Return: |
| 20 | + * - 0 if ways == 0 |
| 21 | + * - 1 if ways == 1 |
| 22 | + * - 2 if ways > 1 |
| 23 | + * |
| 24 | + * A rooted tree is a tree that has a single root node, and all edges are oriented to be |
| 25 | + * outgoing from the root. |
| 26 | + * |
| 27 | + * An ancestor of a node is any node on the path from the root to that node (excluding |
| 28 | + * the node itself). The root has no ancestors. |
| 29 | + */ |
| 30 | + |
| 31 | +/** |
| 32 | + * @param {number[][]} pairs |
| 33 | + * @return {number} |
| 34 | + */ |
| 35 | +var checkWays = function(pairs) { |
| 36 | + const graph = new Map(); |
| 37 | + for (const [x, y] of pairs) { |
| 38 | + if (!graph.has(x)) graph.set(x, new Set()); |
| 39 | + if (!graph.has(y)) graph.set(y, new Set()); |
| 40 | + graph.get(x).add(y); |
| 41 | + graph.get(y).add(x); |
| 42 | + } |
| 43 | + |
| 44 | + const nodes = [...graph.keys()].sort((a, b) => graph.get(b).size - graph.get(a).size); |
| 45 | + const n = nodes.length; |
| 46 | + if (n === 1) return 1; |
| 47 | + |
| 48 | + const root = nodes[0]; |
| 49 | + if (graph.get(root).size !== n - 1) return 0; |
| 50 | + |
| 51 | + let equalDegreeCount = 0; |
| 52 | + for (let i = 1; i < n; i++) { |
| 53 | + const node = nodes[i]; |
| 54 | + let found = false; |
| 55 | + |
| 56 | + for (let j = i - 1; j >= 0; j--) { |
| 57 | + const ancestor = nodes[j]; |
| 58 | + if (graph.get(node).has(ancestor)) { |
| 59 | + for (const neighbor of graph.get(node)) { |
| 60 | + if (neighbor !== ancestor && !graph.get(ancestor).has(neighbor)) { |
| 61 | + return 0; |
| 62 | + } |
| 63 | + } |
| 64 | + if (graph.get(node).size === graph.get(ancestor).size) { |
| 65 | + equalDegreeCount++; |
| 66 | + } |
| 67 | + found = true; |
| 68 | + break; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + if (!found) return 0; |
| 73 | + } |
| 74 | + |
| 75 | + return equalDegreeCount > 0 ? 2 : 1; |
| 76 | +}; |
0 commit comments