Search times for binary search tree

后端 未结 3 1903
太阳男子
太阳男子 2020-12-14 02:55

Does anyone know how to figure out search time for a binary search tree(i.e. worst-case, best-case, and average-case)?

3条回答
  •  眼角桃花
    2020-12-14 03:50

    Might want to tag this one as "homework". Here's a good starting point: http://en.wikipedia.org/wiki/Binary_search_tree

    In general, a balanced binary search tree has a worst-case lookup of O(log n), best case of O(1) (when the desired value is the root) and an average case of O(log n) (the leaves contain exponentially more values than their parents).

    The worst case is the most interesting and is easily seen by recognizing that the first level of a binary tree has 1 node, the second has 2, the third has 4 and so on. Thus, the number of nodes in a binary tree of depth n is precisely 2^n - 1. The mathematical inverse of the exponential function is the logarithm, thus: O(log n).

    An unbalanced tree can be as bad as a linked list and may have a shape like the following:

      1
     / \
        2
       / \
          3
         / \
            4
           / \
    

    In this situation, the worst-case access time is O(n).

提交回复
热议问题