|
| 1 | +/** |
| 2 | + * 1361. Validate Binary Tree Nodes |
| 3 | + * https://leetcode.com/problems/validate-binary-tree-nodes/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have n binary tree nodes numbered from 0 to n - 1 where node i has two children |
| 7 | + * leftChild[i] and rightChild[i], return true if and only if all the given nodes form |
| 8 | + * exactly one valid binary tree. |
| 9 | + * |
| 10 | + * If node i has no left child then leftChild[i] will equal -1, similarly for the right child. |
| 11 | + * |
| 12 | + * Note that the nodes have no values and that we only use the node numbers in this problem. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number} n |
| 17 | + * @param {number[]} leftChild |
| 18 | + * @param {number[]} rightChild |
| 19 | + * @return {boolean} |
| 20 | + */ |
| 21 | +var validateBinaryTreeNodes = function(n, leftChild, rightChild) { |
| 22 | + const parentCount = new Array(n).fill(0); |
| 23 | + let rootCandidate = -1; |
| 24 | + |
| 25 | + for (let i = 0; i < n; i++) { |
| 26 | + if (leftChild[i] !== -1) parentCount[leftChild[i]]++; |
| 27 | + if (rightChild[i] !== -1) parentCount[rightChild[i]]++; |
| 28 | + } |
| 29 | + |
| 30 | + for (let i = 0; i < n; i++) { |
| 31 | + if (parentCount[i] === 0) { |
| 32 | + if (rootCandidate !== -1) return false; |
| 33 | + rootCandidate = i; |
| 34 | + } |
| 35 | + if (parentCount[i] > 1) return false; |
| 36 | + } |
| 37 | + |
| 38 | + if (rootCandidate === -1) return false; |
| 39 | + |
| 40 | + return countNodes(rootCandidate, new Set()) === n; |
| 41 | + |
| 42 | + function countNodes(node, visited) { |
| 43 | + if (node === -1) return 0; |
| 44 | + if (visited.has(node)) return -1; |
| 45 | + visited.add(node); |
| 46 | + const leftNodes = countNodes(leftChild[node], visited); |
| 47 | + const rightNodes = countNodes(rightChild[node], visited); |
| 48 | + if (leftNodes === -1 || rightNodes === -1) return -1; |
| 49 | + return 1 + leftNodes + rightNodes; |
| 50 | + } |
| 51 | +}; |
0 commit comments