i have question for example i want to implement binary tree with array i want understand what will indexes for left child and rigth child ?my array is 0 based i want implement searching in tree using array can anybody help me?
left child = parent * 2 + 1
right child = parent * 2 + 2
I imagine this is homework so I will let you figure out the searching algorithm.
I think you are looking for a heap. Or at least, you use a tree when an array structure is not enough for your needs so you can try to implement a tree inside an array but it wouldn't make much sense since every node contains references to its children without any need of indices.
But an heap is an array that can also be seen as a binary tree, look it out here. It's a tree in the sense that it organizes data as a tree but without having direct references to the children, they can be inferred from the position.
To implement a binary tree as an array you put the left child for node i
at 2*i+1
and the right child at 2*i+2
.
So for instance, having 6 nodes here's the indices of the corresponding array
0
|
---------
| |
---1-- --2--
| | | |
3 4 5 6