【发布时间】:2014-03-26 22:45:37
【问题描述】:
我正在尝试构建 AVL 树,但似乎遇到了节点问题。我尝试创建一个新节点,它将其他节点的所有值更改为我给新节点的任何值。
//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 导入 java.io.; 导入 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);
}
}
【问题讨论】:
-
你知道
static修饰符的含义以及它如何影响类属性吗? -
你也没有将根连接到其他部分的任何节点
-
AvlNode的字段不应是静态的。 -
并非如此。我只知道编译器之前对我很生气,因为事情不是静态的。
-
对。必须注意那些情绪化的编译器:-)。静态意味着某些东西不属于某个类的特定实例。要使用非静态方法或字段,您需要创建一个对象。这样做比让一切都静态化更好。
标签: java data-structures tree nodes avl-tree