所以我对我正在处理的当前问题感到难过。基本上,我需要在基于数组的二叉搜索树中添加一个元素。根据我的文本,它类似于compareTo方法。我甚至不确定要进入哪个方向。对于OOP我是一个完整的菜鸟所以任何帮助都会受到赞赏。
package lab9;
public class BinarySearchTreeArray<E> {
Entry<E> [] tree;
Entry<E> root;
int size;
public BinarySearchTreeArray()
{
tree = null;
size = 0;
}
public int size()
{
return size;
}
public boolean contains(Object obj)
{
Entry<E> temp = root;
int comp;
if (obj == null)
throw new NullPointerException();
while (obj != null)
{
comp = ((Comparable)obj).compareTo (temp.element);
if (comp == 0)
return true;
else if (comp < 0)
temp = temp.left;
else
temp = temp.right;
}//while
return false;
}//contains method
/*
* From the text:
* The definition of the add (E element) method is only a little more
* complicated than the definition of contains (Object obj). Basically,
* the add method starts at the root and branches down the tree
* searching for the element; if the search fails, the element is
* inserted as a leaf.
*/
public void add(E e)
{
Entry<E> node = new Entry<E>(e);
if (tree[parent] == null)
{
tree[0] = node;
size++;
}
else
{
tree[1] = node;
size++;
}
}//add method
/****************************************************************/
protected static class Entry<E>
{
private E element;
private Entry<E> parent, left, right;
public Entry(E e){this.element = element; left = right = null;}
public Entry<E> getLeft(){return left;}
public Entry<E> getRight(){return right;}
}
/****************************************************************/
public static void main(String[] args) {
BinarySearchTreeArray<String> bsta1 = new BinarySearchTreeArray<String>();
BinarySearchTreeArray<Integer> bsta2 = new BinarySearchTreeArray<Integer>();
bsta1.add("dog");
bsta1.add("tutle");
bsta1.add("cat");
bsta1.add("ferrit");
bsta1.add("shark");
bsta1.add("whale");
bsta1.add("porpoise");
bsta2.add(3);
bsta2.add(18);
bsta2.add(4);
bsta2.add(99);
bsta2.add(50);
bsta2.add(23);
bsta2.add(5);
bsta2.add(101);
bsta2.add(77);
bsta2.add(87);
}
}
答案 0 :(得分:3)
确实add方法类似于你的contains方法,在用结构/对象表示的典型二叉树中,你可以使用指针访问左右子树(比如你的示例temp.left和temp.right)。但是,由于数组中有一棵树,你必须访问数组索引,所以问题是:如何访问左/右子树对应的索引?
为此,使用以下表达式left = parent * 2和right = parent * 2 + 1。我将举一个add函数的例子,它将元素添加到整数数组中的树表示,其中-1表示没有值,或者在java中为null。
public void add(E e)
{
Entry<E> node = new Entry<E>(e);
index = 0;
int comp;
boolean not_add = true;
while(not_add)
{
if (tree[index] == null) //if this node is empty
{
tree[index] = node;
size++;
not_add = true;
}
comp = ((Comparable)e).compareTo (tree[index].element);
if(comp == 0) not_add = true; // Same value
else if (comp < 0) index = index * 2; // should be insert on the left
else index = index * 2 + 1; // should be insert on the right
}
}