ArrayList Based Binary Tree - Java

主宰稳场 提交于 2019-12-11 01:09:54

问题


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!


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/12925103/arraylist-based-binary-tree-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!