下面是打印二叉搜索树的无序遍历的代码:公共类BSTPrint {
public void printInorder(BSTNode root){
if (root!=null){
printInorder(root.getLeftNode());
System.out.println(root.getNodeValue());
printInorder(root.getRightNode());
}
}
public static void main(String[] argc){
BSTPrint bstPrint = new BSTPrint();
BSTNode<String> root=new BSTNode<String>();
root.setNodeValue("5");
BSTNode<String> rootLeft= new BSTNode<String>();
rootLeft.setNodeValue("3");
root.setLeftNode(rootLeft);
BSTNode<String> rootRight= new BSTNode<String>();
rootRight.setNodeValue("8");
root.setRightNode(rootRight);
bstPrint.printInorder(root);
}
}
下面是BSTNode类:
public class BSTNode<E> {
private E value;
private BSTNode<E> leftNode=null;
private BSTNode<E> rightNode=null;
public BSTNode getLeftNode(){
return this.leftNode;
}
public void setLeftNode(BSTNode rootLeft){
BSTNode newLeftNode=new BSTNode();
newLeftNode.leftNode=null;
this.leftNode=newLeftNode;
newLeftNode.value=rootLeft;
}
public BSTNode getRightNode(){
return this.rightNode;
}
public void setRightNode(BSTNode rootRight){
BSTNode newRightNode=new BSTNode();
newRightNode.rightNode=null;
this.rightNode=newRightNode;
newRightNode.value=rootRight;
}
public E getNodeValue(){
return this.value;
}
public void setNodeValue(E value){
this.value=value;
}
}
为什么我看到的结果如下所示?
BSTNode@246f9f88
5
BSTNode@1c52ac68
代替
3
5
8
printInOrder
工作正常。左节点的值不是3;左节点的值是另一个节点,因为setLeftNode
:
public void setLeftNode(BSTNode rootLeft){
BSTNode newLeftNode=new BSTNode();
newLeftNode.leftNode=null;
this.leftNode=newLeftNode;
newLeftNode.value=rootLeft;
}
没有将提供的rootLeft
节点连接到this.leftNode
。它正在创建另一个节点作为leftNode
,并将该节点的值设置为rootLeft
。同样的问题出现在setRightNode
.
你需要修复setLeftNode
和setRightNode
。另外,如果您正在使用IDE(例如Eclipse),您知道IDE显示黄色警告指示器的所有地方吗?如果你把鼠标放在它们上面,它会说你没有正确使用泛型?如果您在IDE发出警告时包含了<E>
s,编译器将为您捕获setLeftNode
和setRightNode
中的错误。
你的setleft/right实际上是错误的:
应该是:
public void setRightNode(BSTNode rootRight){
this.rightNode=rootRight;
}
public void setLeftNode(BSTNode rootLeft){
this.leftNode=rootLeft;
}
你已经有了一个节点——所以你只需要设置它。不需要创建额外的节点对象。
提示:如果你看看你的ide中的java警告,你会发现它抱怨你应该参数化你的一些值(总是在BSTNode的所有部分使用BSTNode)。一旦你添加了它,它会告诉你它不能在你设置的*Node函数中将BSTNode转换为E。
对我的Java不新鲜,但我认为你想定义BSTNode
左和右节点成员,像这样:
public class BSTNode<E> {
private E value;
private BSTNode<E> leftNode=null;
private BSTNode<E> rightNode=null;
}