# 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个回答

``````  /** 通过数组构建链表 */
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];
}``````