How to create a Full Binary Tree from an array of Node?
The input is an array of node:
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];
The image of the tree be like below:
The output is a Tree Structure as below:
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,
},
},
};
So far I tried with the program below, but it didn't return the expected Output above.
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);
