|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function preorderTraversal(strArr) |
| 3 | + * take the array of strings stored in strArr, which will represent a binary |
| 4 | + * tree with integer values in a format similar to how a binary heap is |
| 5 | + * implemented with NULL nodes at any level represented with a #. Your goal is |
| 6 | + * to return the pre-order traversal of the tree with the elements separated by |
| 7 | + * a space. For example: if strArr is ["5", "2", "6", "1", "9", "#", "8", "#", |
| 8 | + * "#", "#", "#", "4", "#"] then this tree looks like the following tree: |
| 9 | + * |
| 10 | + * [Image of Example Tree](https://i.imgur.com/Lcy6mtO.png) |
| 11 | + * |
| 12 | + * For the input above, your program should return the string 5 2 1 9 6 8 4 |
| 13 | + * because that is the pre-order traversal of the tree. |
| 14 | + * @param {array} strArr |
| 15 | + * @return {string} |
| 16 | + */ |
| 17 | +function preorderTraversal(strArr) { |
| 18 | + // https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation |
| 19 | + |
| 20 | + const preorderArr = preorder(strArr); |
| 21 | + |
| 22 | + return preorderArr.join(' '); |
| 23 | +} |
| 24 | + |
| 25 | +function preorder(strArr, index = 0) { |
| 26 | + const currentNode = strArr[index]; |
| 27 | + |
| 28 | + if (index >= strArr.length || currentNode === '#') { |
| 29 | + return []; |
| 30 | + } |
| 31 | + |
| 32 | + const left = preorder(strArr, 2 * index + 1); |
| 33 | + const right = preorder(strArr, 2 * index + 2); |
| 34 | + |
| 35 | + const nodeAndChildren = []; |
| 36 | + nodeAndChildren.push(currentNode, ...left, ...right); |
| 37 | + |
| 38 | + return nodeAndChildren; |
| 39 | +} |
| 40 | + |
| 41 | +module.exports = preorderTraversal; |
0 commit comments