0

Some references as in link1 say there are 2n+1 nodes. Whereas some say there are roughly 4n nodes link2.

To me 2n+1 seems intuitive as for a perfect binary tree with n leaves has 2n+1 nodes and when the tree is not perfect it must be less than 2n+1 nodes. No idea how space complexity is O(4n).

1 Answers1

0

The space complexity of a Segment Tree is O(n).

In a typical Segment Tree you have 2n - 1 nodes. You have exact n leave nodes, and in order to connect all those leaves up to a tree you need n-1 additional nodes (similar argument to why a tree with n nodes has n-1 edges).

There are however some implementations of Segments Trees, that use 4n nodes. E.g. the recursive implementation from https://cp-algorithms.com/data_structures/segment_tree.html uses 4n nodes, in order to have a simpler indexing of the nodes. While the iterative implementation from https://codeforces.com/blog/entry/18051 uses 2n-1 nodes. (Notice, it's also possible to implement the recursive version with 2n-1 nodes. In fact the linked website even discusses such an approach.)

Jakube
  • 3,353
  • 3
  • 23
  • 40