Complexity of inserting n numbers into a binary search tree

余生长醉 提交于 2019-11-30 15:20:43

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:

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.

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!