如何在Java中设置/为父节点设置子节点,子节点的子节点等等?
我有一个班EightPuzzle
。如何在Java中设置/为父节点设置子节点,子节点的子节点等等?
public class EightPuzzle {
int[][] board = new int[3][3];
//code here
}
如果我有一个类Node<T>
其中T
为对象EightPuzzle
的。如果我有一个Node<EightPuzzle> parent
,我该如何设置它的孩子?它的孩子的孩子?等等,如果孩子是ArrayList<Node<EightPuzzle>>
?
public class Node<T> {
private List<Node<T>> children = new ArrayList<Node<T>>();
private Node<T> parent = null;
private T data = null;
public Node(T data) {
this.data = data;
}
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public List<Node<T>> getChildren() {
return children;
}
public void setParent(Node<T> parent) {
parent.addChild(this);
setParentInternal(parent);
}
public void setParentInternal(Node<T> parent){
this.parent = parent;
}
public void addChild(T data) {
addChild(new Node<T>(data));
}
public void addChild(Node<T> child) {
child.setParentInternal(this);
this.children.add(child);
}
//may not use this and set data
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public boolean isRoot() {
return (this.parent == null);
}
public boolean isLeaf() {
if(this.children.size() == 0)
return true;
else
return false;
}
public void removeParent() {
this.parent = null;
}
您可能希望对下面的东西使用递归方法。
例子:
public void assignChildren(Node node) {
List<Node> children = ... // somehow decide the children here
node.setChildren(children);
// This is just a for each loop using a java 8 method reference
// to make a recursive call
children.forEach(this::assignChildren);
}
编辑: 搬进答案
评论如果您不能setChildren(...)
方法添加到您的类,那么你永远可以遍历孩子把它们添加到节点一个接一个
对不起,当我只完成了一半的工作时,意外地提交了滴答声和单调的答案。如果你不能在你的类中添加一个'''setChildren(...)'''方法,那么你总是可以迭代将它们添加到节点的子节点。 –
你需要递归的基本情况。 –
如果有些事情需要添加,您可以编辑您的答案。 – 4castle
你想要设置什么? – 4castle
试图设置parent.children与对象EightPuzzle并设置他们的孩子等 –
您是否尝试过创建'节点'对象并将它们与'addChild'或'setParent'连接在一起?我不明白你卡在哪里。 – 4castle