Why in a heap implemented by array the index 0 is left unused?

后端 未结 4 1978
无人及你
无人及你 2020-12-23 04:12

I\'m learning data structures and every source tells me not to use index 0 of the array while implementing heap, without giving any explanation why. I searched the web, sear

4条回答
  •  不思量自难忘°
    2020-12-23 04:43

    (While I was searching, I came up with an answer of my own but I don't know whether it's correct or not.)

    If index 0 is used for the root node then subsequent calculations on its children cannot proceed, because we have indexOfLeftChild = indexOfParent * 2 and indexOfRightChild = indexOfParent * 2 + 1. However 0 * 2 = 0 and 0 * 2 + 1 = 1, which cannot represent the parent-children relationship we want. Therefore we have to start at 1 so that the tree, represented by array, complies with the mathematical properties we desire.

提交回复
热议问题