我试图在我的自定义BST中插入节点。第一次调用insertData方法时,新节点以root身份正确插入。问题发生在第二次和后续调用中。在BST中插入一个节点
下面是我的代码:
1.节点类=
package ishan.trees.tree;
class Node implements Comparable<Node> {
private int data;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
private Node leftChild;
private Node rightChild;
public Node(int data,Node leftChild,Node rightChild)
{
this.data=data;
this.leftChild=leftChild;
this.rightChild=rightChild;
}
@Override
public int compareTo(Node o) {
if(o.getData() > this.data)
return -1;
if(o.getData() < this.data)
return 1;
return 0;
}
}
Tree类=
package ishan.trees.tree;
public class Tree {
private Node root=null;
public Node getRoot() {
return root;
}
public void insertData(int data)
{
Node node=new Node(data,null,null);
insert(node,this.root);
}
private Node insert(Comparable<Node> node,Node root1)
{
if(root1==null)
{//insert as first element ie root
this.root=new Node(((Node)node).getData(),null,null);
}
else if(node.compareTo(root1) <0)
{
root1.setLeftChild(insert(node,root1.getLeftChild()));
}
else if(node.compareTo(root1) >0)
{
root1.setLeftChild(insert(node,root1.getRightChild()));
}
return root1;
}
}
3.主要类=
包ishan.trees 。用法;
import ishan.trees.tree.Tree;
public class Usuage {
public static void main(String a[])
{
Tree tree=new Tree();
tree.insertData(10); //---------1
tree.insertData(15); //---------2
tree.insertData(9); //---------3
tree.insertData(4); //---------4
}
}
当调试第二调用它是这样的:
insertData(15){ 插入件(15,10) }
这使得调用insert方法---->
插入(15,NULL)
每次我得到这个空,这导致当前节点替换袋鼠t节点。
我无法弄清楚为什么在调用过程中,root1引用为空而不是指向我的根?
更多信息:
从insertData在通话过程中它()来插入()。说我在第二次调用insertData(15)时,我打电话插入(15,this.root) - > insert(node,root1)。但是这个root1引用原来是null.but当我检查this.root它指的是正确的根节点。
谢谢!
好的...所以我调试它错了。感谢您的帮助:) – 2014-10-10 11:27:34