Advantages of Binary Search Trees over Hash Tables

前端 未结 18 891
醉酒成梦
醉酒成梦 2020-11-29 15:02

What are the advantages of binary search trees over hash tables?

Hash tables can look up any element in Theta(1) time and it is just as easy to add an element....but

相关标签:
18条回答
  • 2020-11-29 15:31

    A (balanced) binary search tree also has the advantage that its asymptotic complexity is actually an upper bound, while the "constant" times for hash tables are amortized times: If you have a unsuitable hash function, you could end up degrading to linear time, rather than constant.

    0 讨论(0)
  • 2020-11-29 15:31

    A binary tree is slower to search and insert into, but has the very nice feature of the infix traversal which essentially means that you can iterate through the nodes of the tree in a sorted order.

    Iterating through the entries of a hash table just doesn't make a lot of sense because they are all scattered in memory.

    0 讨论(0)
  • 2020-11-29 15:32

    Binary search trees can be faster when used with string keys. Especially when strings are long.

    Binary search trees using comparisons for less/greater which are fast for strings (when they are not equal). So a BST can quickly answer when a string is not found. When it's found it will need to do only one full comparison.

    In a hash table. You need to calculate the hash of the string and this means you need to go through all bytes at least once to compute the hash. Then again, when a matching entry is found.

    0 讨论(0)
  • 2020-11-29 15:36

    A hashtable would take up more space when it is first created - it will have available slots for the elements that are yet to be inserted (whether or not they are ever inserted), a binary search tree will only be as big as it needs to be. Also, when a hash-table needs more room, expanding to another structure could be time-consuming, but that might depend on the implementation.

    0 讨论(0)
  • 2020-11-29 15:37

    The main advantages of a binary tree over a hash table is that the binary tree gives you two additional operations you can't do (easily, quickly) with a hash table

    • find the element closest to (not necessarily equal to) some arbitrary key value (or closest above/below)

    • iterate through the contents of the tree in sorted order

    The two are connected -- the binary tree keeps its contents in a sorted order, so things that require that sorted order are easy to do.

    0 讨论(0)
  • 2020-11-29 15:38

    If you want to access the data in a sorted manner, then a sorted list has to be maintained in parallel to the hash table. A good example is Dictionary in .Net. (see http://msdn.microsoft.com/en-us/library/3fcwy8h6.aspx).

    This has the side-effect of not only slowing inserts, but it consumes a larger amount of memory than a b-tree.

    Further, since a b-tree is sorted, it is simple to find ranges of results, or to perform unions or merges.

    0 讨论(0)
提交回复
热议问题