尝试在此BST中创建一个root:
if (currentNode == null) {
currentNode = new BinaryNode(newInt);
System.out.println(currentNode);
System.out.println(newInt);
//System.out.println(newInt.getValue());
System.out.println("Node Null, made root");
}else{
println用于调试。但是我遇到了问题,因为这是输出:
BinaryNode@7004ba66
4
Node Null, made root
BinaryNode@4669b7fe
6
Node Null, made root
BinaryNode@46aea8cf
1
Node Null, made root
BinaryNode@74ccd249
3
Node Null, made root
BinaryNode@3301f287
2
Node Null, made root
BinaryNode@44d9973a
8
Node Null, made root
BinaryNode@29578426
7
Node Null, made root
BinaryNode@30a4effe
5
Node Null, made root
BinaryNode@1c8825a5
9
Node Null, made root
这让我觉得它没有像它应该那样识别(currentNode == null)。有什么想法吗?
完整的pastebin:here
任何帮助都非常感谢:)
答案 0 :(得分:2)
问题在于,当您指定currentNode
时,root
不会被分配。
Java按值传递变量,这意味着值或引用的副本将传递到您的方法中。在这种情况下,currentNode
方法的形式参数insertNode
会传递root
方法返回的getRoot
字段的副本。
要解决此问题,您应该将insertNode
方法分成两部分:
public void insert(int newInt);
和
private BinaryNode insert(int newInt, BinaryNode node);
公共方法应该在没有getRoot
参数的情况下使用(类中插入树的用户永远不需要传递根,否则他们可以通过在中间传递一个节点来破坏你的树数字应该在不同的分支中。)
私有方法应该返回旧节点或新节点。你应该像这样使用它:
public void insert(int newInt) {
root = insert(newInt, root);
}
如果传入的node
为null
,则方法本身应返回新节点。当node
不为null时,该方法应返回传入的节点。
就outputList
问题而言,您应该使用StringBuffer
而不是String
来构建输出。与String
不可变的StringBuilder
不同,append
是可变的。它允许您更改其中的字符串(使用+=
而不是{{1}})。
答案 1 :(得分:1)
您没有分配到树的根目录。将其更改为:
if (root== null) {
root= new BinaryNode(newInt);