Commit 06dcfc7e authored by ccottier's avatar ccottier

array to binary search tree algo added

parent 1503bcb8
......@@ -160,6 +160,36 @@ document.addEventListener("DOMContentLoaded", ()=> {
something();
} while (undefined);
//algo: sorted array to balanced binary search tree
class Node {
constructor(val,left,right){
this.val = val;
this.left = left;
this.right = right;
}
}
class BinaryTreeMaker {
static makeTree(sortedArr){
const midPoint = Math.floor(sortedArr.length / 2);
const root = new Node(sortedArr[midPoint], null, null);
const leftSide = sortedArr.slice(0, midPoint);
const rightSide = sortedArr.slice(midPoint + 1);
if (leftSide.length){
root.left = this.makeTree(leftSide);
}
if (rightSide.length){
root.right = this.makeTree(rightSide);
}
return root;
}
}
console.log(BinaryTreeMaker.makeTree([3,6,8,9,10,100,433]));
console.log("we are at the conclusion, thanks for your time.")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment