我会提到,这是作业。我非常困惑我需要做些什么才能使add()函数正常工作。令人困惑的是,我们需要将左右子项定义为BinaryTree
类型,并且add()函数采用String
而不是Node
,我在本网站的每个示例中都会看到这一点。我想不出如何设置一个字符串到一个新的孩子,这是一个BinaryTree类型。Java - 非常困惑这个递归二叉树
任何帮助&指导表示赞赏。
import java.util.*;
public class BinaryTree {
private String data;
private BinaryTree leftChild;
private BinaryTree rightChild;
public BinaryTree() {
data = null;
leftChild = null;
rightChild = null;
}
public BinaryTree(String d) {
data = d;
leftChild = null;
rightChild = null;
}
public BinaryTree(String d, BinaryTree left, BinaryTree right) {
data = d;
leftChild = left;
rightChild = right;
}
public String getData() { return data; }
public BinaryTree getLeftChild() { return leftChild; }
public BinaryTree getRightChild() { return rightChild; }
public void setData(String d) { data = d; }
public void setLeftChild(BinaryTree left) { leftChild = left; }
public void setRightChild(BinaryTree right) { rightChild = right; }
public String root;
//This function is what I'm stuggling with
public void add(String item){
if(root==null)
{
root = item;
}
else
{
String tmp = root; // save the current root
if(root.compareTo(item)>0)
{
setData(item);
add(item); //I should have setBinaryTree(item) here, but I can't convert type String to BinaryTree?.
}
else if(root.compareTo(item)<0)
{
setData(item);
add(item);
}
root = tmp; // put the root back to its original value
}
return;
}
}