Convert array to complete binary tree

class Node {
constructor(value) {
this.data = value;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
inOrderTraversal() {
const traverse = (root) => {
if (root == null) {
return;
}
traverse(root.left);
console.log(root.data);
traverse(root.right);
}
traverse(this.root);
}
}
function createCompleteBinaryTreeFromArray(arr) {
const length = arr.length;
const binaryTree = new BinaryTree();
const traverseAndReplace = (root, i) => {
if (i < length) {
root = new Node(arr[i]);
root.left = traverseAndReplace(root.left, 2 * i + 1);
root.right = traverseAndReplace(root.right, 2 * i + 2);
}
return root;
}
binaryTree.root = traverseAndReplace(binaryTree.root, 0);
return binaryTree;
}
const result = createCompleteBinaryTreeFromArray([1, 2, 3, 4, 5, 6, 6, 6, 6]);result.inOrderTraversal();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ujjwal Gupta

Ujjwal Gupta

Frontend lead Polygon | Creator of jsstore, mahaljs | sqlweb, fortjs | opensource creator | we3, blockchain, solidity | javascript