Complexity of inserting n numbers into a binary search tree

前端 未结 2 2049
长发绾君心
长发绾君心 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-02 16:42

    What wiki is saying is correct. Since the given tree is a BST, so one need not to search through entire tree, just comparing the element to be inserted with roots of tree/subtree will get the appropriate node for th element. This takes O(log2n). Once we have such a node we can insert the key there bht after that it is required push all the elements in the right aub-tree to right, so that BST's searching property does not get violated. If the place to be inserted comes to be the very last last one, we need to worry for the second procedure. If note this procedure may take O(n), worst case!. So the overall worst case complexity of inserting an element in a BST would be O(n). Thanks!

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