把节点变成树,用层序遍历
function createNode(data) {
return {
data: data || null,
left: null,
right: null
}
}
var dataArr = [1,
2, 3,
null, 5, null, 6,
7];
var t=toTree(dataArr);
function toTree(dataArr) {
var cur=createNode( dataArr[0]);
var queue=[];
queue.push(cur);
for (var i = 1; i < dataArr.length; i += 2) {
var item=queue.shift();
if( dataArr[i] ){
item.left=createNode( dataArr[i]);
queue.push(item.left);
}
if( dataArr[i+1] ){
item.right=createNode( dataArr[i+1]);
queue.push(item.right);
}
}
return cur;
}
console.log(t)