Last active
April 23, 2020 22:34
-
-
Save gkucmierz/3a990d4652503c013e9429caff963d05 to your computer and use it in GitHub Desktop.
convert array to BST - binary search tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arrayToBst = arr => { | |
const [LEFT, VALUE, RIGHT] = [0, 1, 2]; | |
const node = [null, null, null] | |
const bst = node.slice(); | |
arr.map(el => { | |
let tmp = bst; | |
while (tmp[VALUE] !== null) { | |
const branch = el < tmp[VALUE] ? LEFT : RIGHT; | |
if (tmp[branch] === null) { | |
tmp[branch] = node.slice(); | |
} | |
tmp = tmp[branch]; | |
} | |
tmp[VALUE] = el; | |
}); | |
return bst; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment