Last active
November 16, 2020 03:48
-
-
Save HallexCosta/e5e6a6e23da1e732f48463e6862f0695 to your computer and use it in GitHub Desktop.
Example of use the binary tree data structure with JavaScript
This file contains 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
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