[英]Creating a Generic Binary Search Tree in Java
我正在尝试用Java创建此Tree,但是卡住了,无法弄清楚如何继续。 这是我到目前为止的代码:
public class BTNode<E>
{
private E data;
private BTNode<E> left;
private BTNode<E> right;
public BTNode(E newData, BTNode<E> newLeft, BTNode<E> newRight)
{
setData(newData);
setLeft(newLeft);
setRight(newRight);
}
public E getData()
{
return data;
}
public BTNode<E> getLeft()
{
return left;
}
public BTNode<E> getRight()
{
return right;
}
public void inorderPrint()
{
if(left != null)
left.inorderPrint();
System.out.println(data);
if(right != null)
right.inorderPrint();
}
public void setData(E newData)
{
data = newData;
}
public void setLeft(BTNode<E> newLeft)
{
left = newLeft;
}
public void setRight(BTNode<E> newRight)
{
right = newRight;
}
}
public class Tree<E extends Comparable<E>>
{
private BTNode<E> root;
private int manyNodes;
public Tree()
{
}
public void add(E element)
{
BTNode<E> newLeft = null;
BTNode<E> newRight = null;
if(root == null)
root = new BTNode<E>(element, newLeft, newRight);
else
{
BTNode<E> cursor = new BTNode<E>(element, newLeft, newRight);
cursor = root;
boolean done = false;
while(done = false)
{
if (element.compareTo(cursor.getData()) <= 0)
{
if(cursor.getLeft() == null)
{
cursor.setLeft(element); //create a new node from left
done = true;
}
else
cursor = cursor.getLeft();
}
else
{
if(cursor.getRight() ==null)
{
cursor.setRight(element); //create a new node from right
done = true;
}
else
cursor = cursor.getRight();
}
}
}
}
public int size()
{
return manyNodes;
}
public BTNode<E> getRoot()
{
return root;
}
}
问题是创建左节点和右节点,因为类型不同,这没有让我失望。 另外我不确定在Tree构造函数中要放什么。
方法
public void setLeft(BTNode<E> newLeft) {
left = newLeft;
}
public void setRight(BTNode<E> newRight) {
right = newRight;
}
期待BTNode
对象,但是您像这样调用它们
cursor.setLeft(element);
就编译器而言, element
是E
类型,而E
是扩展Comparable<E>
的类型。 您的类型不匹配。 将您的element
包装在BTNode
对象中并传递它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.