4 ms·
The binary tree example is fine for very small and completely balanced trees, but for anything else you're going to get a lot of undefined entries in the array.
by DougWebb 16y ago
The binary tree example is fine for very small and completely balanced trees, but for anything else you're going to get a lot of undefined entries in the array. There's no need for this; the array elements can be data structures like:
{ 'data': data, 'left': null, 'right': null }
When you insert a new child, you can just push it onto the end of the array, find its parent by comparing the 'data' values, and set the parent's 'left' or 'right' to point to the child's index in the array. Update the child's 'left' or 'right' as needed if the child isn't a leaf.
He mentions that you can build a traditional binary tree out of objects, but he makes it sound a lot more complicated than it actually is. His implementation of a binary tree breaks down at a scale where it's probably simpler and nearly as fast to just use an associative array and linear traversal, and he still requires writing the insertion, removal, and traversal methods.
- ntownsend 16y agoIn JavaScript, Arrays are not actually arrays. They're not a contiguous block of memory. They're just Objects (i.e. hash tables) that key on integers. If you look at the indices it will look like you have a bunch of undefined elements in the array, but no memory has actually been consumed for those indices in the array so nothing is wasted.
- DougWebb 16y agoExcellent point. I forget that javascript doesn't really have arrays, just array syntax. My example is much more appropriate in other languages with true arrays and the ability to store object references in them.