If n keys 1,2,…,n are to be inserted in that order,
(a). to a normal BST (Binary Search Tree)
(b). to a Splay Tree
What would be the complexity in each case (a), b) ?
Is it O(log n) for both the cases? Or is it O(log n) for (a) and O(M log n) for (b) ?
According to the Wikipedia Splay tree article, average insertion time is O(log n), and worst case is amortized O(log n). So your expected time to insert all the items into the Splay tree would be O(n log n).
The Binary search tree case depends on what kind of BST you're using. For a primitive BST, inserting items in order is the worst case because it creates a degenerate tree--a linked list. That's O(n) (where n is the number of items in the tree) per insertion. So insertion of all the items would require O(n^2).
Insertion into a degenerate tree is O(n) because the tree is essentially a linked list. After inserting the numbers [1, 2, 3]
in order, your tree looks like this:
1
\
2
\
3
If you then want to insert 4
, the code has to look at each of the existing items, 1, 2, and 3, before adding 4 as the right child of 3. And when you go to insert 5
, it again has to look at the previous four items. Each insertion has to look at all of the previous items. The total number of comparisons when inserting n items will be (n*(n-1))/2
, which is O(n^2).
If you're using a self balancing binary search tree, then insertion is O(log n), and insertion of all the items will require O(n log n).