Array representation of a binary tree
Data-structures #binary-tree #data-structuresIf a binary tree is represented by array then for any node present at index i, it’s left child will be at (i * 2) + 1, right will be at (i * 2) + 2 and prent will be at ⌊(i - 1) / 2⌋.
node = i
left-node = (i * 2) + 1
right-node = (i * 2) + 2
parent-node = ⌊(i - 1) / 2⌋ // floor value
Example 1.
When a
complete binary treeis represented by an array (as in this example) then it willalwayshave consecutivenon-nullvalues on the left side of the array but it can havenullsat the end of array
Example 2.
Note that even the left nodes of
2and7are not in the tree but still there should be an index reserved for these nodes. For example, if3(right child of2) is stored at index4then it will become left child of node7which is wrong.