사용자 정의 BST에 노드를 삽입하려고합니다. 처음으로 insertData 메소드가 호출되면 새 노드가 루트로 올바르게 삽입됩니다. 두 번째 및 후속 호출에서 문제가 발생합니다. 다음은 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;
}
}
트리 클래스 =
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.Main 클래스 =
패키지 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) }
로 삽입 메소드를 호출한다---->
인서트 (15, NULL)
I이 널 매번하세요 이것은 타나 교체 현재 노드 초래 t 노드.
전화를 걸 때 root1 참조가 null이고 내 루트를 가리키지 않는 이유를 알아낼 수 없습니까?
추가 정보 : insertData에서 통화 중
그것()을 삽입하는(). say insertData (15)를 두 번째로 호출하는 동안 insert (15, this.root) -> insert (node, root1)를 호출합니다. 하지만이 root1 참조가 null로 밝혀졌습니다.하지만이 루트를 검사 할 때 정확한 루트 노드를 나타냅니다.
고마워요!
좋아 ... 그래서 내가 잘못 디버깅했다.도움을 주셔서 감사합니다 :) –