Skip to content

Instantly share code, notes, and snippets.

@HallexCosta
Last active November 16, 2020 03:48
Show Gist options
  • Save HallexCosta/e5e6a6e23da1e732f48463e6862f0695 to your computer and use it in GitHub Desktop.
Save HallexCosta/e5e6a6e23da1e732f48463e6862f0695 to your computer and use it in GitHub Desktop.
Example of use the binary tree data structure with JavaScript
const tree = {}
function add(tree, value) {
if (tree.value) {
if (value > tree.value) {
add(tree.right, value)
} else {
add(tree.left, value)
}
} else {
tree.value = value
tree.right = {}
tree.left = {}
}
}
console.log("Init Tree", tree)
add(tree, 10)
console.log("Tree Inserted #1", tree)
add(tree, 11)
console.log("Tree Inserted #2", tree)
add(tree, 9)
console.log("Tree Inserted #3", tree)
/*
OUTPUT:
Tree Inserted #3
{
value:10,
right: {
value:11,
right:(0) {...},
left:(0) {...}
},
left: {
value:9,
right:(0) {...},
left:(0) {...}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment