Implementing a Binary Heap 4. Parent Index

If you reverse engineer the formula for the right children, it should be (node - 2) // 2 given the formula in the previous screen. Just wanted to check if this was intentional and I may have misunderstood the concept?

1 Like

Hi @siddhip987

Please attach a link to the screen/ course page. Thanks.

1 Like
1 Like

Hey @siddhip987

This may be intentional as the content tries to provide the same solution for both left and right child nodes in one go.
Notice for (i - 1) / 2 always works for the left index as it is always an odd number. This doesn’t work for the right index as it’s always an even number (the index I mean!).

If we apply (i - 2) / 2 as a general solution then the right indexed nodes will work correctly but the left ones will give 0.5 errors similar to case 1.

If we apply (i - 2) // 2 as a general solution then again the left indexed nodes would result in 1 less index for parents. For example for left index 7, the parent node will be ( 7 - 2) // 2 = 2 which is incorrect.

If you are implementing separate solutions then i - 1 and i - 2 might work. I guess the intention of the content was to provide the same solution that can be applied to either index.

please do share your thoughts.

1 Like