# binary trees

• 11-17-2011
Animesh Gaitond
binary trees
i hav started started studying binary trees.i m stuck with one problem,which is as follows:-
1)create a binary tree(not a binary search tree) in C using elements from a array[25] such that for every index m , left child is the 2m index value in array and right child will be in 2m+1-th index

for example:- For a node A[3] the left child is the A[2*3] index element and right child is in A[(2*3) +1 ] th position. So left child of A[3] is A[6] and right is A[7].
and similarly for other nodes.
please help me solving the above problem as i thought a lot over it but could n't find a good solution.
• 11-17-2011
laserlight
Err... what do you find problematic about it?
• 11-17-2011
Animesh Gaitond
i dont know how to create this kind of tree ,beacuse if i want to insert
A[6], it should become left child of A[3] , i cant understand the logic behind the problem;
array A[25] contains integers (random)
the tree should look like this
A[1]
/ \
A[2] A[3]
/ \ / \
A[4] A[5] A[6] A[7]
• 11-17-2011
laserlight
Quote:

Originally Posted by Animesh Gaitond
i cant understand the logic behind the problem

The idea is that the links are implied by the order of the elements in the array. So to insert at index 6, you insert at index 6. That is all there is to it (for now). Now, if you are asked to print the elements in pre-order, for example, then you follow the "links" by performing the index calculations for the child nodes.
• 11-17-2011
Animesh Gaitond
how should the function of creating the tree look like?how will recursion take place in the given function?
• 11-17-2011
laserlight
Quote:

Originally Posted by Animesh Gaitond
how should the function of creating the tree look like?

Since there are apparently no constraints on the elements, you can simply treat it as insertion into an array, and that is what it is.

Quote:

Originally Posted by Animesh Gaitond
how will recursion take place in the given function?

Using simple arithmetic: if you know the index of the root of the subtree, you can access its children by computing their indices.