|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function TreeConstructor(strArr) take |
| 3 | + * the array of strings stored in strArr, which will contain pairs of integers |
| 4 | + * in the following format: (i1,i2), where i1 represents a child node in a tree |
| 5 | + * and the second integer i2 signifies that it is the parent of i1. For example: |
| 6 | + * if strArr is ["(1,2)", "(2,4)", "(7,2)"], then this forms the following tree: |
| 7 | + * |
| 8 | + * [Image of Example Tree](https://i.imgur.com/NMRdSO1.png) |
| 9 | + * |
| 10 | + * which you can see forms a proper binary tree. Your program should, in this |
| 11 | + * case, return the string true because a valid binary tree can be formed. If a |
| 12 | + * proper binary tree cannot be formed with the integer pairs, then return the |
| 13 | + * string false. All of the integers within the tree will be unique, which means |
| 14 | + * there can only be one node in the tree with the given integer value. |
| 15 | + * |
| 16 | + * https://www.coderbyte.com/results/bhanson:Tree%20Constructor:JavaScript |
| 17 | + * |
| 18 | + * @param {array} strArr |
| 19 | + * @return {string} 'true' or 'false' |
| 20 | + */ |
| 21 | +function treeConstructor(strArr) { |
| 22 | + // Convert ['(1,2)','(2,4)','(5,7)','(7,2)','(9,5)'] |
| 23 | + // format to [[1,2],[2,4],[5,7],[7,2],[9,5]] |
| 24 | + const pairs = strArr.map(str => str.match(/[\d]+/g).map(Number)); |
| 25 | + |
| 26 | + const nodesWithNoParents = []; |
| 27 | + for (let i = 0; i < pairs.length; i++) { |
| 28 | + if (numChildren(pairs, pairs[i][0]) > 2) { |
| 29 | + return 'false'; |
| 30 | + } |
| 31 | + if (numParents(pairs, pairs[i][1]) === 0) { |
| 32 | + nodesWithNoParents.push(pairs[i][1]); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + const uniqueNodesWithNoParents = new Set(nodesWithNoParents); |
| 37 | + |
| 38 | + if (uniqueNodesWithNoParents.size !== 1) { |
| 39 | + return 'false'; |
| 40 | + } |
| 41 | + return 'true'; |
| 42 | + |
| 43 | + function numChildren(pairs, number) { |
| 44 | + let count = 0; |
| 45 | + pairs.forEach(pair => { |
| 46 | + if (pair[1] === number) { |
| 47 | + count++; |
| 48 | + } |
| 49 | + }); |
| 50 | + return count; |
| 51 | + } |
| 52 | + |
| 53 | + function numParents(pairs, number) { |
| 54 | + let count = 0; |
| 55 | + pairs.forEach(pair => { |
| 56 | + if (pair[0] === number) { |
| 57 | + count++; |
| 58 | + } |
| 59 | + }); |
| 60 | + return count; |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +module.exports = treeConstructor; |
0 commit comments