令人困惑的部分原因是“Node”不应该是插入方法的参数,您应该调用在节点中定义的插入方法。
因此,假设您在“正常代码”中持有“根”节点 - 我们称其为“rootNode”,只是为了模糊。
好了,你的代码插入到树将是:
rootNode.insert(newValue);
很容易的。
现在定义该方法。
public class Node {
private int value;
private Node lower;
private Node higher;
public void insert(int newValue) {
if (newValue < value)
if(lower == null)
lower=new Node(value);
else
lower.insert(newValue);
else
if(higher == null)
higher=new Node(value);
else
higher.insert(newValue);
}
// and you'll need a constructor
public Node(int value) {
this.value=value;
}
}
这应该更清楚。我要打“Post”,然后我要编辑它,并弄清楚如何轻松折射这个邪恶的邪恶副本&粘贴代码。
第二个想法,我会留在那里,因为它更具可读性。我能看到的最好的解决方法是使节点的数组,然后你:
public class Node {
private int value;
private Node[] nodes=new Node[2];
private final int LOWER=0;
private final int HIGHER=1;
public void insert(int newValue) {
int index=LOWER;
if (newValue > value)
index=HIGHER;
if(nodes[index] == null)
nodes[index]=new Node(value);
else
nodes[index].insert(newValue);
}
}
但我不会取代原来的,因为,正如我所说,它更清晰。
我推荐这本重构书。一旦你真的得到面向对象,它确实有助于简化你的代码。将一个对象传递给静态方法(不使用成员变量的方法)是一种无用的方式。
关于@ ted的评论和OO的更多考虑 - getLeft和getRight不应该成为问题。在抽象之外不是必需的。
一般来说你可能需要在节点这些方法:
public boolean doesContain(int value) {
if(value == this.value)
return true
else
return nodes[ this.value < value ? LOWER : HIGHER].doesContain(value);
}
,也许
public void getValuesSorted(LinkedList l) {
nodes[LOWER].getValuesSorted(l);
l.put(value);
nodes[HIGHER].getValuesSorted(l);
}
然后,你甚至都不需要公开,它是你正在处理与 - 一棵树 - 拜托OO抽象。
请注明你得到的例外,不只是你在哪里得到它。 – 2011-04-06 02:02:42
这里是tree.BinaryTree.insert(BinaryTree.java:22)除外即时得到在线程异常 “主” 显示java.lang.NullPointerException \t \t在tree.BinaryTree.insert(BinaryTree.java:15) \t在driver.Driver.main(Driver.java:16) – thunderousNinja 2011-04-06 02:05:48