# leetcode上tree树类型的题目，是怎么样根据数组实例化tree的，如下图和代码

• 1.2k

## 问题

leetcode上tree树类型的题目，是怎么样根据数组实例化tree的，如下图和代码

## 自己的想法

``````        var root = [1, 2, 5, 3, 4, null, 6];
function TreeNode(val, left, right) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
var tree = new TreeNode(1, 2, 5)
tree.left = new TreeNode(2, 3, 4)
tree.right = new TreeNode(5, null, 6)
console.log('tree', tree);
console.log('tree', JSON.stringify(tree));``````

## 疑问

##### 2个回答
``数组中的内容为层序遍历的结果,其中如果只有一个子节点，则为下一层添加一个null以判断该节点唯一的子节点是左子节点还是右子节点``

``````class TreeNode {
val: number = 0
left: TreeNode | null = null
right: TreeNode | null = null

constructor(val: number) {
this.val = val
}
}

const build = (data: (number | null)[]): TreeNode | null => {
if (!data.length || data[0] === null) return null

let ans
let cur = (ans = new TreeNode(data[0]!))
const parentQueue: TreeNode[] = []

data.shift()
parentQueue.push(cur)
while (data.length) {
const root = parentQueue.shift()!
const left = data.shift()
const right = data.shift()

if (typeof left === 'number') {
root.left = new TreeNode(left)
parentQueue.push(root.left)
}

if (typeof right === 'number') {
root.right = new TreeNode(right)
parentQueue.push(root.right)
}
}

return ans
}``````