0

When constructing a segment tree, why it needs to be a full binary tree? I took some example input arrays and when made them to complete binary tree i am getting the same minimum in a range result. Then why make it a full binary tree when complete binary tree is also giving the same result. Input array- 1, 3, 5, 7, 9, 11

Braj
  • 588
  • 3
  • 15
  • (Beware (fundamentally) different definitions of *segment tree*: best present the one you are using (with (possibly mutually contradictory) references).) – greybeard Aug 26 '17 at 13:52

2 Answers2

2

The array representation of the segment tree for example array 1, 3, 5, 7, 9, 11 can be stored like (assuming the range query is finding the minimum element)

Sorry for a lazy diagram.

enter image description here

The number of tree nodes is calculated as pow*2-1 where pow = smallest power of 2 greater than or equal to n.

Clearly the above segment tree representation is a full binary tree and not a complete binary tree.

Can you share your segment tree array representation how are you storing it as a complete binary tree?

Amit Rastogi
  • 926
  • 2
  • 12
  • 22
  • A full binary IS a complete binary tree – user5965026 Mar 13 '21 at 02:03
  • @user5965026, no, it's not always necessary. There are full binary trees which are not complete. – E. Shcherbo Mar 20 '21 at 14:44
  • @E.Shcherbo I think there's some inconsistent definitions across resources. I've always understood a full binary tree as a tree in which every level is completely filled, which would mean it's a complete binary tree as well, but there's some definitions of full binary tree where every node just has exactly 2 children, except for the leaves, which would not necessarily be a complete binary tree. – roulette01 Mar 29 '21 at 16:39
  • @roulette01 I agree about inconsistency. What you're saying about is known to me as a perfect binary tree https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees – E. Shcherbo Mar 30 '21 at 08:34
  • @E.Shcherbo Actually, I think I may have misremembered. I think I got "full" and "perfect" binary tree confused. With that said, I still find it kind of confusing to remember all the different names for trees, especially when there isn't uniformly among resources. – roulette01 Mar 30 '21 at 23:39
2


A segment tree is not a complete binary tree. For a binary tree to be complete, all levels except the last one need to be completely filled. Also, for the last level, nodes should be as left as possible. Considering your input array with 6 elements, the tree will be as follows ( assuming 1-6 indices):-enter image description here

Clearly, the last level has leaf nodes 1 and 2 followed by missing nodes that could have been children of node 3 (hypothetically) and then leaf nodes 4 and 5. This level has missing nodes with nodes 4 and 5 not as left as possible. Whereas, every node has either 0 or 2 children making it a full binary tree.

varshika03
  • 71
  • 3