Complexity of inserting n numbers into a binary search tree

前端 未结 2 2050
长发绾君心
长发绾君心 2021-01-02 15:48

I have got a question, and it says \"calculate the tight time complexity for the process of inserting n numbers into a binary search tree\". It does not denote whether this

2条回答
  •  -上瘾入骨i
    2021-01-02 16:29

    It could be O(n^2) even if the tree is balanced.

    Suppose you're adding a sorted list of numbers, all larger than the largest number in the tree. In that case, all numbers will be added to the right child of the rightmost leaf in the tree, Hence O(n^2).

    For example, suppose that you add the numbers [15..115] to the following tree:

    enter image description here

    The numbers will be added as a long chain, each node having a single right hand child. For the i-th element of the list, you'll have to traverse ~i nodes, which yields O(n^2).

    In general, if you'd like to keep the insertion and retrieval at O(nlogn), you need to use Self Balancing trees.

提交回复
热议问题