2014-03-26 53 views
0

我正在嘗試構建AVL樹,但似乎遇到節點問題。我嘗試創建一個新節點,並將其他節點的所有值更改爲我給新節點的值。創建新節點不斷更改所有節點(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; 
     } 

    } 
} 

這裏就是我使用上述用於: //Tree.java 進口java.io. ; import 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

你知道靜態修飾符意味着什麼以及它如何影響類屬性嗎? – BackSlash

+0

你還沒有將根連接到其他部分的任何節點 –

+0

'AvlNode'的字段不應該是靜態的。 –

回答

1

對不起,我剛纔的評論相當簡短。你的問題是AvlNode內的這兩行。

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

這意味着,每一個AvlNode具有相同的值,這四個領域。這意味着樹的每個節點只有一個key和一個height;並且樹的每個節點只有一個左後裔和只有一個右後裔。您確實需要刪除那些static修飾符,以便每個AvlNode實例都可以擁有其自己的這四個字段的副本。