简体   繁体   中英

Creating new node keeps changing all nodes (Java)

I am trying to build an AVL tree, but seem to be having a problem with nodes. I try to make a new node and it changes all the values of other nodes to whatever I was giving the new node.

//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;
       }

   }
}

And here is what I am using the above for: //Tree.java import 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); 

    }
}

Sorry for being rather brief with my earlier comment. Your problem is these two lines inside AvlNode .

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

That implies that every AvlNode has the same value, for each of these four fields. That would mean that there's only one key , and one height for every node of the tree; and only one left descendant and only one right descendant of every node of the tree. You really need to remove those static modifiers, so that every AvlNode instance can have its own copies of these four fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM