共计 705 个字符,预计需要花费 2 分钟才能阅读完成。
数组转成链表
class TreeNode {constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function arrayToTree(arr) {function toNode(item) {// 转换数组项至节点
if (item === null || item === undefined) {return null}
else {return new TreeNode(item) }
}
let queue = [];
const tree = toNode(arr.shift());
queue.push(tree);// 入队列第一个元素
while (arr.length > 0) {
// 当数组里还有项的时候就拿数组的项去填充队列
let current = queue.shift();
current.left = toNode(arr.shift());
current.right = toNode(arr.shift());
if (current.left) {queue.push(current.left) }
if (current.right) {queue.push(current.right) }
}
return tree;
}
// var arr = [3, 9, 20, null, null, 15, 7]
// var arr = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1];
// var arr = [3, 1, 4, null, 2]
var arr = [5, 3, 6, 2, 4, null, null, 1]
var data = new arrayToTree(arr)
console.log('data', data);
正文完