【发布时间】:2016-05-05 18:19:56
【问题描述】:
我想出了以下尝试在 java 中创建通用树:
import java.util.*;
public class GeneralNode<T>{
private T data = null;
private Vector<GeneralNode<T>> children =
new Vector<GeneralNode<T>>();
public GeneralNode(){
this(null);
}
public GeneralNode(T d){
data = d;
}
public Vector<GeneralNode<T>> getChildren(){
return children;
}
public void addChild(T d){
GeneralNode<T> c = new GeneralNode<T>(d);
this.children.add(c);
}
public void addChild(GeneralNode<T> c){
this.children.add(c);
}
public T getData(){
return data;
}
public void setData(T newData){
data = newData;
}
public boolean isLeaf(){
return(children.isEmpty());
}
public Vector getChildrenData(){
Vector<T> result = new Vector<T>();
for(int i = 0; i < children.size(); i++)
result.add(children.elementAt(i).getData());
return result;
}
}
这非常适合存储信息。它允许我创建一个节点并在该节点中插入更多节点,以及在每个节点中具有一种类型的信息。不幸的是,似乎我无法使用此类引用“父”节点。本质上,我将向量嵌套在向量中,因此我实际上无法引用包含该节点的节点。
我确定我必须创建一个单独的 GeneralTree 类才能完成这项工作,但我不确定我将如何去做。我有将根分配为 GeneralNode 的想法,并将“上一个”和“下一个”节点分别作为父节点和子节点。到目前为止,这是我想出的:
import java.util.*;
public class GeneralTree<T>{
private GeneralNode<T> root;
private GeneralNode<T> parent;
private GeneralNode<T> children;
public GeneralTree(){
this(null);
}
public GeneralTree(T d){
this(d, null);
}
/* I don't know what to do here. I want
* to assign a parent node to every
* tree I make, but if I keep the
* second parameter as GeneralNode<T>, wouldn't
* that mean I could only ever have one GeneralTree?
*/
public GeneralTree(T d, GeneralNode<T> p){
root = new GeneralNode<T>(d);
parent = p;
}
}
我已经在我很困惑的构造函数上写了 cmets。我希望我已经很好地解释了我的问题。如果有人可以帮助我,那就太好了。
【问题讨论】:
-
如果你想让节点知道他们的父节点是谁,那么你必须给类另一个成员,每个实例在其中存储一个引用它的父节点,并且你必须在添加节点时管理这些引用。为了使其可靠地工作,您必须避免其他对象能够直接将节点添加到任何节点的子节点列表中。这意味着
getChildren()不能返回children列表本身——它可以返回一个副本或不可变的包装器。