Skip to content

Commit 8310d92

Browse files
committed
Added medium/preorder_traversal
1 parent 8c76ac2 commit 8310d92

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

medium/preorder_traversal.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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;

medium/preorder_traversal.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const preorderTraversal = require('./preorder_traversal');
2+
3+
describe('preorderTraversal()', () => {
4+
test('correctly returns preorder traversal given binary heap', () => {
5+
expect(preorderTraversal(['4', '1', '5', '2', '#', '#', '#'])).toBe(
6+
'4 1 2 5'
7+
);
8+
expect(preorderTraversal(['2', '6', '#'])).toBe('2 6');
9+
});
10+
});

0 commit comments

Comments
 (0)