Skip to content

Instantly share code, notes, and snippets.

@zhanhongtao
Created August 3, 2019 14:32
Show Gist options
  • Save zhanhongtao/2bbbbdbb3def588fcb20a230cac5596e to your computer and use it in GitHub Desktop.
Save zhanhongtao/2bbbbdbb3def588fcb20a230cac5596e to your computer and use it in GitHub Desktop.
function TreeNode(val) {
this.val = val
this.left = this.right = null
}
module.exports = function list2tree(list) {
let tree = null
let length = list.length
let padding = 0
let nodes = []
for (let i = 0; i < length; ++i) {
let val = list[i]
let node = val ? new TreeNode(val) : null
nodes[i + padding] = node
if (i === 0) tree = node
else {
let p
let fixed = 0
while (p == null) {
padding += fixed * 2
index = Math.floor((i + padding - 1) / 2)
p = nodes[index]
fixed = 1
}
if (p) {
p[(i & 1) ? 'left' : 'right'] = node
}
}
}
nodes.length = 0
nodes = null
return tree
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment