Created
July 25, 2018 08:36
-
-
Save tahmidsadik/a7aaa3f7c1332dd21b0ab1e5883e8062 to your computer and use it in GitHub Desktop.
Dumbed down binary search tree, with only insert operation :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let tree = { root: { val: null, left: null, | |
right: null | |
} | |
}; | |
const createEmptySubtree = () => ({ val: null, left: null, right: null }); | |
const insert = (node, root) => { | |
console.log(`node: ${node}, root: ${root}`); | |
if (!root.val) { | |
console.log("on root"); | |
root.val = node; | |
} else if (node < root.val) { | |
// go left | |
if (!root.left) { | |
root.left = createEmptySubtree(); | |
} | |
insert(node, root.left); | |
} else if (node > root.val) { | |
// go right | |
if (!root.right) { | |
root.right = createEmptySubtree(); | |
} | |
insert(node, root.right); | |
} | |
}; | |
insert(10, tree.root); | |
insert(50, tree.root); | |
insert(5, tree.root); | |
insert(29, tree.root); | |
console.log(tree); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment