3

"Every comparison-based algorithm to sort n elements must take Ω(nlogn) comparisons in the worst case. With this fact, what would be the complexity of constructing a n-node binary search tree and why?"

Based on this question, I am thinking that the construction complexity must be at least O(nlogn). That said, I can't seem to figure out how to find the total complexity of construction.

L. F.
  • 16,219
  • 7
  • 33
  • 67
Jake
  • 31
  • 2
  • 1
    I think this question fits better on https://cstheory.stackexchange.com – Eduardo Pascual Aseff Mar 25 '20 at 20:10
  • 1
    Of course it depends if you are making efforts to keep the tree balanced (e.g., AVL, RedBlack, Splay, randomized binary search trees). O(n log(n)) is worst case for AVL and RedBlack, average case for randomized BST's, and amortized case for Splay. If sorting is your goal, a heap would be preferred over BST which gives O(n log(n)). – wcochran Mar 25 '20 at 20:16
  • @Daniele If the tree is *not* balanced (e.g., keys are inserted in order) then each insertion is O(n), which results in O(n^2) total. – wcochran Mar 25 '20 at 20:40
  • 1
    @EduardoPascualAseff Probably cs.stackexchange.com rather than cstheory.stackexchange.com. – Jim Mischel Mar 26 '20 at 17:17

2 Answers2

2

The title of the question and the text you quote are asking different things. I am going to address what the quote is saying because finding how expensive BST construction is can be done just by looking at an algorithm.

Assume that for a second it was possible to construct a BST in better than Ω(nlogn). With a binary search tree you can read out the sorted list in Θ(n) time. This means I could create a sorting algorithm as follows.

Algorithm sort(L) 
  B <- buildBST(L)
  Sorted <- inOrderTraversal(B)
  return Sorted

With this algorithm I would be able to sort a list in better than Ω(nlogn). But as you stated this is not possible because Ω(nlogn) is a lower bound. Therefor it is not possible to create a binary search tree in better than Ω(nlogn) time.

Furthermore since an algorithm exits to create a BST in O(nlogn) time you can actually say that the algorithm is optimal under the comparison based model

Mitch
  • 2,960
  • 1
  • 13
  • 27
0

The construction of the BST will be O(n(log(n))).
You will need to insert each and every node which is an O(n) operation.
To insert that n nodes you will need to make at least O(log(n)) comparisons.
Hence the minimum will be O(n(log(n))).
Only in the best case where the array is already sorted the time complexity will be O(n)

Pritam Banerjee
  • 15,297
  • 10
  • 71
  • 92
  • 1
    Actually, to insert each node you need to make *at most* O(log(n)) comparisons. A sorted array does not give you O(n) BST creation. There are still many cases where O(log n) comparisons are required to find the correct insertion point. – Jim Mischel Mar 26 '20 at 17:13