Created
August 21, 2018 22:05
-
-
Save w8r/f71a5ba5b9b7ff4c46505d53a8124a27 to your computer and use it in GitHub Desktop.
Non-recursive BST build from sorted array
This file contains 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
export default function sortedArrayToBST(data) { | |
let root = {}; | |
const Q = [root]; | |
const stack = [0, data.length - 1]; | |
while (Q.length !== 0) { | |
const right = stack.pop(); | |
const left = stack.pop(); | |
const cur = Q.pop(); | |
const mid = left + ((right - left) >> 1); | |
if (left - right === 0) { | |
cur.data = data[mid]; | |
} else { | |
if (left < mid) { | |
cur.left = {}; | |
Q.push(cur.left); | |
stack.push(left, mid); | |
} | |
if (right > mid) { | |
cur.right = {}; | |
Q.push(cur.right); | |
stack.push(mid + 1, right); | |
} | |
} | |
} | |
return root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment