Created
August 3, 2019 14:32
-
-
Save zhanhongtao/2bbbbdbb3def588fcb20a230cac5596e to your computer and use it in GitHub Desktop.
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
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