Search code examples
data-structuressegment-tree

Proof that height of segment tree is ceil(log(n))


I was reading up on this Quora answer on memory space required by segment trees. In the second paragraph, the author assumes that the height of a segment tree is ceil(log(n)), where n is the size of the array from which the tree is being formed.

After going through a few examples, I noticed that whenever n is a power of 2, the last level of the segment tree contains segments of size 1. Whenever n exceeds this power of 2, some segments of size 1 on this level become segments of size 2, increasing the height of the tree by 1, in accordance with the above formula for height.

But I can't seem to figure out a strict proof that the height of a segment tree is ceil(log(n)). Any help would be appreciated.


Solution

  • One way to show this is to prove the following: if n ≤ 2k, then a segment tree for an array of n elements has height at most k. Then, since n = 2lg n ≤ 2⌈lg n⌉, we get that a segment tree for n nodes has height at most ⌈lg n⌉.

    We can show that this inequality holds by induction on k. As a base case, the only n where n ≤ 20 is n = 1, and a segment tree for n = 1 items consists of just a single node, which has height 0.

    For the inductive step, suppose the claim is true for k. Now pick an n where n ≤ 2k+1. The segment tree consists of a root node with two subarrays of sizes ⌊n/2⌋ and ⌈n/2⌉. You can show that both of these quantities are bounded from above by 2k (the floor case is easy; the ceiling case is a little more subtle than it looks), so we can apply the IH to get that the segment trees for those subarrays each have height at most k. Combining that with the root node gives a segment tree of height at most k+1, as needed.