【发布时间】:2021-06-30 15:13:02
【问题描述】:
如何从节点数组创建完整的二叉树?
输入是一个节点数组:
const arr1 = [3, 5, 1, 6, 2, 9, 8, null, null, 7, 4];
const arr2 = [3, 5, 1, 6, 7, 4, 2, null, null, null, null, null, null, 9, 8];
树的图像如下:
输出是一个树结构如下:
const expectedOutput = {
val: 3,
left: {
val: 5,
left: {
val: 6,
left: null,
right: null,
},
right: {
val: 2,
left: { val: 7, left: null, right: null },
right: { val: 4, left: null, right: null },
},
},
right: {
val: 1,
left: {
val: 9,
left: null,
right: null,
},
right: {
val: 8,
left: null,
right: null,
},
},
};
到目前为止,我尝试使用下面的程序,但它没有返回上面的预期输出。
你能帮忙吗?我对其他解决方案持开放态度。谢谢。
const arr1 = [3, 5, 1, 6, 2, 9, 8, null, null, 7, 4];
const arr2 = [3, 5, 1, 6, 7, 4, 2, null, null, null, null, null, null, 9, 8];
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
function createTree(arr, rootIndex = 0, childIndex = 0) {
if (arr[rootIndex] === null) {
return null;
} else if (childIndex + 1 < arr.length) {
childIndex++;
const leftChildIndex = childIndex;
childIndex++;
const rightChildIndex = childIndex;
return new TreeNode(
arr[rootIndex],
createTree(arr, leftChildIndex, childIndex),
createTree(arr, rightChildIndex, childIndex)
);
} else {
return new TreeNode(arr[rootIndex], null, null);
}
}
const output = createTree(arr1);
console.log(output);
编辑 感谢@Wyck 的回答。还有另一个简单的解决方案。
以下示例
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function createTree(arr, i) {
if (i < arr.length && arr[i] !== null) {
const node = new Node(arr[i]);
node.left = createTree(arr, 2 * i + 1);
node.right = createTree(arr, 2 * i + 2);
return node;
}
return null;
}
const arr = [3, 5, 1, 6, 2, 9, 8, null, null, 7, 4];
const tree = createTree(arr, 0);
console.log(tree);
【问题讨论】:
-
您的实际问题或问题是什么?
-
"我在正确传递 childIndex 时遇到问题" 什么样的问题?
标签: javascript arrays binary-tree