2013-05-07 4 views
0

바이너리 트리를 구현하려고하는데 루트를 사용하지 않습니다. 어떤 아이디어? 루트가 잘 삽입되어야하는 것처럼 보이지만 인쇄 할 때 null이 생깁니다. "고정"하지 않는 트리에 임시 노드 만 추가하려고합니까?바이너리 트리 구현하기

public class tree { 
    public static void main(String args[]){ 
     Treeb tree = new Treeb(); 
     tree.add(10); 
     tree.add(20); 
     tree.add(2); 
     tree.add(6); 
     tree.printTree(); 
    } 
} 
class Node{ 
    int data; 
    Node left; 
    Node right; 
    public Node(int data){ 
     this.data = data; 
     left = null; 
     right = null; 
    } 
    Node getLeft(){ 
     return left; 
    } 
    Node getRight(){ 
     return right; 
    } 
} 

class Treeb{ 
    Node root; 
    Treeb(){ 
     root = null; 
    } 

    void add(int n){ 
     addNode(n, root); 
    } 

    void addNode(int n, Node vert){ 
     if(vert == null){ 
      vert = new Node(n); 
     } 
     else if(vert.left.data < n){ 
      if(vert.left == null){ 
       vert.left = new Node(n); 
      } 
      else{ 
       addNode(n, vert.left); 
      } 
     } 
     else if(vert.right.data >= n){ 
      if(vert.right == null){ 
       vert.right = new Node(n); 
      } 
      else{ 
       addNode(n,vert.right); 
      } 
     } 
    } 
    void printTree(){ 
     if(root != null){ 
      printChild(root); 
     } 
     System.out.println(root); 
    } 
    void printChild(Node leaf){ 
     System.out.print(leaf.data); 
     if(leaf.left != null){ 
      printChild(leaf.getLeft()); 
     } 
     if(leaf.right != null){ 
      printChild(leaf.getRight()); 
     } 
    } 
} 
+2

안녕하세요, 답변 옆에 2 개의 작은 메모가 있습니다. 클래스 이름은 대문자로 시작하며 개인과 같은 수식어를 사용하는 것이 좋을 때 좋습니다. 또한 getter (getLeft() 및 getRight())를 만들 때 인스턴스 변수 대신에 getter()를 사용하는 것이 좋습니다. (물론 이것은 'private'수정자를 사용하지 않았기 때문에 가능했습니다.) –

답변

3

귀하의 방법 addNode(int, Node)이 작동하지 않습니다.

첫째 :

if(vert == null){ 
    vert = new Node(n); 
} 

당신은 지역 변수에 새 노드를 할당하고 있습니다. 따라서 새로운 Node는 메소드의 끝에서 버려집니다.

둘째 : vertnull이없는 경우 당신이 NPE를 얻을 것입니다, 그래서

} 
else if(vert.left.data < n){ 
    // code 
} 
else if(vert.right.data >= n){ 

vert.leftvert.rightnull 될 수 있습니다.

3

getLeft()getRight() (것) 언젠가 null을 반환합니다. printChild()에서 leaf 자체가 null이 아닌지 확인해야합니다. (아마도 NPEleafnull이므로 if(leaf.left != null)에 도착했습니다. rootnull 인 경우 다시 트리 구조를 다시 고려해야 할 수 있습니다.

4

vert에 새 참조를 지정하지만 root이 아니라는 이유는 null입니다.