2014-03-26 1 views
0

AVL 트리를 만들려고하지만 노드에 문제가있는 것 같습니다. 나는 새로운 노드를 만들려고 노력하고 그것은 새로운 노드에주고 있던 다른 노드의 모든 값을 변경합니다. //Tree.java 수입 java.io 패키지 :새 노드 만들기가 모든 노드를 계속 변경합니다. (Java)

//AVL.java 
import java.util.*; 
import java.io.*; 

public class AVL{ 
    static AvlNode root; 

    public static void tree(int[] list){ 
     for(int i=0; i<list.length; i++){ 
     insertPrep(list[i]); 
     } 
    } 


    public static void insertPrep(int data){ 
     //if not null insert data into existing root node otherwise make new node using data 
     if (root==null){root = new AvlNode(data);} 
     else { 
      System.out.println("inPr else"); 
      System.out.println(root.key + " & " + data); 
      AvlNode newNode = new AvlNode(data); 
      System.out.println(root.key + " & " + newNode.key); 

     } 
    } 

    //where tree is made and stored 
    static class AvlNode{ 
     static int key, height; //data for input numbers and height for height of nodes to keep balance 
     static AvlNode left, right; //left for left side of tree and right for right side of tree  

     AvlNode(int data){ 
      key = data; 
     } 

    } 
} 

그리고 여기에 내가 대해 위의를 사용하고 무엇인가 ; 가져 오기 java.util.;

public class Tree{ 

    public static void main(String[] args){ 

     int n = 10; //numbers to be in array 
     int a[] = new int[n]; //first array 

     for (int i=0; i<n; i++){ 
     a[i] = i+1; //insert #'s 1-n; smallest to largest 

     } 

     AVL.tree(a); 

    } 
} 
+2

'static' 수정 자의 의미와 클래스 속성에 미치는 영향을 알고 있습니까? – BackSlash

+0

또한 else 부분의 노드에 루트를 연결하지 않습니다. –

+0

'AvlNode'의 필드는 정적이어서는 안됩니다. –

답변

1

불편을 끼쳐 드려 죄송합니다. 이 두 줄은 AvlNode 안에 있습니다.

static int key, height; 
static AvlNode left, right; 

즉, 모든 AvlNode에는 이러한 4 개의 필드 각각에 대해 동일한 값이 있음을 의미합니다. 즉, 트리의 모든 노드에 대해 keyheight 중 하나만 있다는 것을 의미합니다. 트리의 모든 노드에서 오직 하나의 자손과 유일한 자손 만 남았습니다. 모든 AvlNode 인스턴스가이 네 필드의 자체 복사본을 가질 수 있도록 해당 static 수정자를 제거해야합니다.

관련 문제