Suppose there is a binary tree like the one below that should be stored in an array.
7 / \ 1 10 /\ 9 11
And I found that the formula for storing nodes in an array starts by saving the root of the node at position 0, and then for each node with index i its children are placed at indexes (i*2)+1 and (i*2)+2 , And if the index of any of them is greater than array.length - 1 , then node has no children.
So, I start by placing 7 at position 0, then his children 1 and 10 at positions i2 + 1 and i2 + 2, which will be 1 and 2:
|7|1|10| | | | 0 1 2 3 4 5
Now I am stuck with node 1 that has no children. What should I put as my children?
Is it possible to put a default value that will mean the absence of a node, for example, -1, for example:
|7|1|10|-1|-1|9|11| 0 1 2 3 4 5 6 7
Vcode source share