LeetCode 数组转二叉树
(参考文档)[www.xiabingbao.com/post/js/lee…]
// 二叉树
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
// [1, null, 2, null, null, 3, null]是标准格式 数组->二叉树
function array2BinaryTree(arr, index = 0) {
if (index >= arr.length || arr[index] === null) {
return null;
}
const root = new TreeNode(arr[index]);
root.left = array2BinaryTree(arr, 2 * index + 1);
root.right = array2BinaryTree(arr, 2 * index + 2);
return root;
}
// [1, null, 2, 3] 是串行化格式 数组->二叉树
function deserialize(data) {
if (!data || data.length === 0) {
return null;
}
let root = new TreeNode(data[0]);
let queue = [root];
let i = 1;
while (i < data.length) {
let node = queue.shift();
if (data[i] !== null) {
node.left = new TreeNode(data[i]);
queue.push(node.left);
}
i++;
if (i < data.length && data[i] !== null) {
node.right = new TreeNode(data[i]);
queue.push(node.right);
}
i++;
}
return root;
};