# 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
}``````

``````  /** 通过数组构建链表 */
public static TreeNode build(Integer[] data) {
TreeNode[] nodes = new TreeNode[data.length];
nodes[0] = new TreeNode(data[0]);

for (int i = 1; i < data.length; i++) {
if (data[i] == null) {
continue;
}
// 计算父节点索引位置
int parentNodeIndex = (i - 1) / 2;

TreeNode node = new TreeNode(data[i]);
nodes[i] = node;
if (parentNodeIndex * 2 + 1 == i) {
nodes[parentNodeIndex].left = node;
} else {
nodes[parentNodeIndex].right = node;
}
}
return nodes[0];
}``````
##### 撰写回答
###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进