Advantages of Binary Search Trees over Hash Tables

前端 未结 18 1052
醉酒成梦
醉酒成梦 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:22

    Binary search trees are good choice to implement dictionary if the keys have some total order (keys are comparable) defined on them and you want to preserve the order information.

    As BST preserves the order information, it provides you with four additional dynamic set operations that cannot be performed (efficiently) using hash tables. These operations are:

    1. Maximum
    2. Minimum
    3. Successor
    4. Predecessor

    All these operations like every BST operation have time complexity of O(H). Additionally all the stored keys remain sorted in the BST thus enabling you to get the sorted sequence of keys just by traversing the tree in in-order.

    In summary if all you want is operations insert, delete and remove then hash table is unbeatable (most of the time) in performance. But if you want any or all the operations listed above you should use a BST, preferably a self-balancing BST.

提交回复
热议问题