2

I am currently in the process of implementing an ArrayList based binary tree in Java. I am trying to figure out how this would be done, but I am running into a wall. There are a bunch of methods in a class I am supposed to implement, but each time I try something, it doesn't seem to work.

We have Position objects that are identified by Position<E>. In this class we have an array list that is private, and a root variable, both accessible only by this class, so the size() method, and the isEmpty() methods are simple. However, I am running into some trouble when it comes to implementing the methods such as: hasLeft(Position<E>), hasRight(Position<E>) left(Position<E>), right(Position<E>), addRoot(E e), etc... The Left and Right methods simply return the left child and right child of a node. I am familiar with ArrayList, but not when it comes to implementing a binary tree class with them.

How would I go about implementing these methods? I am stuck, and I would appreciate any help I can get.

Thanks!

2
  • Could you show the interface you are supposed to implement? Commented Oct 16, 2012 at 23:56
  • It is simply public interface Position<E> { E element(); } Commented Oct 17, 2012 at 1:09

2 Answers 2

2

When you write binary trees as an Array you are building what's typically called a heap. Heaps are fairly well documented and this article will give you lots of detail about how they are implemented:

http://en.wikipedia.org/wiki/Binary_heap

Sign up to request clarification or add additional context in comments.

Comments

0

You can build a binary tree on the top of a contiguous array. Basically, having a 0 based index, for an element on the i th position of the array:

left(i) : 2 * i + 1
right(i) : 2 * i + 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.