如果题目说的是“用层序数组构建二叉树”,核心就是:
- 下标为
i的节点 - 左孩子下标是
2 * i + 1 - 右孩子下标是
2 * i + 2
class TreeNode {
constructor(val) {
this.val = val
this.left = null
this.right = null
}
}
function arrayToBinaryTree(arr) {
if (!arr.length || arr[0] == null) return null
const build = (index) => {
if (index >= arr.length || arr[index] == null) return null
const node = new TreeNode(arr[index])
node.left = build(2 * index + 1)
node.right = build(2 * index + 2)
return node
}
return build(0)
}例如:
arrayToBinaryTree([1, 2, 3, 4, 5, null, 7])会构造成这样一棵树:
1
/ \
2 3
/ \ \
4 5 7需要注意的是,这和面试里另一类常见题“平铺数组转树形结构(parentId → children)”不是同一道题。