class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {}
static createTreeNode(arr, index) {
if (index > arr.length) {
return null;
}
if (arr[index] == null) {
return null;
}
const node = new TreeNode(arr[index]);
node.left = BinaryTree.createTreeNode(arr, index * 2 + 1);
node.right = BinaryTree.createTreeNode(arr, index * 2 + 2);
return node;
}
static arrayToTree(arr) {
if (arr.length === 0) {
return null;
}
const root = new TreeNode(arr[0]);
let isLChild = true;
const queue = [];
queue.push(root);
for (let i = 1; i < arr.length; i++) {
const node = queue[0];
if (isLChild) {
if (arr[i] != null) {
node.left = new TreeNode(arr[i]);
queue.push(node.left);
}
isLChild = false;
} else {
if (arr[i] != null) {
node.right = new TreeNode(arr[i]);
queue.push(node.right);
}
queue.shift();
isLChild = true;
}
}
return root;
}
}