0

Although the time complexity of building a min heap looks like O(nlogn), it can be proved that it is O(n).

Why can't we apply the same logic and say the time complexity of a balanced binary search tree is also O(n).

AV94
  • 1,654
  • 2
  • 19
  • 32
  • (Time complexity of building a balanced BST depends on input data, too: Ο(n) *if* your n input items are ordered (and, depending on details, randomly accessible).) – greybeard Dec 10 '17 at 11:20

1 Answers1

2

Beside the fact that BST provides order, while heap only ensures that element is greater than those below (for max-heap), the complexity of building the heap depends on the building strategy. This wiki image demonstrates it clearly.

If you use siftDown (bottom-up) approach, complexity is O(n), while with siftUp is O(nlogn), just like in BST.

Why can't we apply the same logic and say the time complexity of a balanced binary search tree is also O(n)?

Bottom-up approach for building a heap is not applicable for BST unless the input list is already sorted, but in this case you already have O(nlogn) complexity because of sorting.

Miljen Mikic
  • 13,521
  • 5
  • 51
  • 59