So you are to implement a procedure getIndex(int index)
which has to return you the node with that index?
If so, you are looking for an efficient way to represent a binary tree.
You could traverse the tree for each call to getIndex
but this wouldn't be efficient...
An efficient solution is to store the complete binary tree in an array, because of the O(1) access it provides. Store a node n at index n in the array and its child nodes at index 2*n
and (2*n) - 1
. But here the restrictions are that the tree has to be complete and the size of an array is not variable (if the binary tree becomes too big, a bigger array (usually twice as big) should be made and all elements should be copied).
This is a handy solution because :
- Node access is in O(1) but a procedure like
addNode()
would become amortized in O(1). (*)
- A node does not have to remember it's child nodes -->
this.left
becomes this.left()
with the implementation of left()
provided below.
A possible implementation for left()
procedure.
static int[] binaryTreeArray = new int[maxTreeSize]; // BT of integers for example
...
public int left() { // returns integer or ... (type of your nodes)
return binaryTreeArray[(this.Index)*2]; // O(1)
}
(*) An addNode()
-like procedure would add nodes in O(1) (binaryTreeArray[index] = nodeValue;
) most of the time but when the binaryTreeArray
is full it will have to make a bigger array that is usually twice as big (O(n) for the copying). It can be shown that this has an amortized cost of O(1) but this has no added value for this answer.