# 生成树
在leetcode上通过给定的数组,如何生成二叉树
function generateTree(arr) {
const tree = [[{val: arr[0]}]];
for(let i = 1, deep = 1; i < arr.length; deep++) {
// console.log(i)
const before = tree[deep - 1]
let beforeI = 0;
const tmp = [];
const maxJ = before.filter(it => it).length * 2;
// console.log('maxJ',maxJ, before)
for(let j = 0; j < maxJ; j++) {
while(!before[beforeI]) {
beforeI++;
}
const it = arr[i + j];
const item = (it === null || typeof it === "undefined") ? null : {val: it}
if (j % 2 === 0) {
if (before[beforeI]) {
before[beforeI].left = item;
}
} else {
if (before[beforeI]) {
before[beforeI].right = item;
}
beforeI ++;
}
tmp.push(item)
}
i+=Math.pow(2, deep);
tree.push(tmp)
}
return tree[0][0]
}
console.log(generateTree([1,2,3]))
console.log(generateTree([5,4,8,11,null,13,4,7,2,null,null,null,1]))