gpt4 book ai didi

java - 用 Java 创建通用二叉搜索树

转载 作者:行者123 更新时间:2023-12-01 13:51:08 25 4
gpt4 key购买 nike

我正在尝试用 Java 创建这棵树,但我陷入困境,不知道如何继续。这是我到目前为止的代码:

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类型为EE就编译器而言,是扩展 Comparable<E> 的类型。您的类型不匹配。包裹你的elementBTNode对象并传递它。

关于java - 用 Java 创建通用二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19944845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com