我使用树形数据结构是为了解决在java中实现树形数据结构期间的特定问题。我将节点放在一个类中,并将它们设置为静态的,因为这是在互联网上给出的一些建议,但我不确定是否强制将其设置为静态的,以及将其设置为静态的好处是什么。
import java.util.*;
import java.io.*;
class tree{
node root;
static class node{
int data;
node left_child;
node right_child;
public node(int data){
this.data=data;
left_child=null;
right_child=null;
}
}
}发布于 2019-07-23 17:47:14
首先,您应该遵循Java大写标准。这意味着:
类名称中每个单词的第一个字母都是大写的,LikeThis
likeThis(),
static关键字将变量与类关联,而不是与类的特定实例关联。这可能不是您想要的。树的一个非常基本的实现是:
class Tree {
private Tree right;
private Tree left;
private int data;
// getters/setters/constructors etc
}然后,您需要将其初始化为:
public static void main(String[] args) {
Tree tree = new Tree();
tree.setRight(new Tree());
tree.setLeft(new Tree());
tree.setValue(5);
// continue as needed, probably use a loop though
}发布于 2019-07-23 18:19:17
在本例中,您将node用作嵌套类static
static class node{
int data;
node left_child;
node right_child;
public node(int data){
this.data=data;
left_child=null;
right_child=null;
}
}
}因为这个类在树形类中。如果你想删除static,你必须在一个单独的文件中创建这个Node类,并且你可以在树类中导入这个类。
例如,在test包中创建以下两个类
package test;
import test.Node;
public class Tree {
public static void main(String args[]) {
Node node = new Node();
}
}和Node类为
package test;
public class Node{
int data;
Node next;
@Override
public String toString() {
return "Node [data=" + data + ", next=" + next + "]";
}
}https://stackoverflow.com/questions/57161141
复制相似问题