Why lookup in a Binary Search Tree is O(log(n))?

后端 未结 5 1569
失恋的感觉
失恋的感觉 2021-01-31 18:20

I can see how, when looking up a value in a BST we leave half the tree everytime we compare a node with the value we are looking for.

However I fail to

5条回答
  •  误落风尘
    2021-01-31 19:22

    If we have a tree of N elements, why the time complexity of looking up the tree and check if a particular value exists is O(log(n)), how do we get that?

    That's not true. By default, a lookup in a Binary Search Tree is not O(log(n)), where n is a number of nodes. In the worst case, it can become O(n). For instance, if we insert values of the following sequence n, n - 1, ..., 1 (in the same order), then the tree will be represented as below:

                      n
                     /
                  n - 1
                   /
                n - 2
                 /
               ...
               1
    

    A lookup for a node with value 1 has O(n) time complexity.

    To make a lookup more efficient, the tree must be balanced so that its maximum height is proportional to log(n). In such case, the time complexity of lookup is O(log(n)) because finding any leaf is bounded by log(n) operations.

    But again, not every Binary Search Tree is a Balanced Binary Search Tree. You must balance it to guarantee the O(log(n)) time complexity.

提交回复
热议问题