我想出了以下内容作为在 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;
}
}
这对于存储信息非常有用。它允许我创建一个节点并在该节点中插入更多节点,并在每个节点中包含一种类型的信息。不幸的是,我似乎无法引用此类的“父”节点。本质上,我将 vector 嵌套在 vector 中,因此我实际上无法引用保存该节点的节点。
我确信我必须创建一个单独的 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;
}
}
我已经对我感到困惑的构造函数写了评论。我希望我已经很好地解释了我的问题。如果有人能帮助我解决这个问题那就太好了。
最佳答案
正如@JohnBollinger所说,您可以在每个节点内保留父节点的引用。如果这样做,则必须在 addChild
方法中设置父节点。
import java.util.Vector;
public class GeneralNode<T>{
private T data = null;
private Vector<GeneralNode<T>> children =
new Vector<GeneralNode<T>>();
private GeneralNode<T> parentNode;
//constructors
private void setParent(GeneralNode<T> parentNode) {
this.parentNode = parentNode;
}
public void addChild(T d){
GeneralNode<T> c = new GeneralNode<T>(d);
c.setParent(this);
this.children.add(c);
}
public void addChild(GeneralNode<T> c){
c.setParent(this);
this.children.add(c);
}
//other methods
}
关于java - 我请求有关在 Java 中实现通用树的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37057576/