我有一個班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;
}
你想要設置什麼? – 4castle
試圖設置parent.children與對象EightPuzzle並設置他們的孩子等 –
您是否嘗試過創建'節點'對象並將它們與'addChild'或'setParent'連接在一起?我不明白你卡在哪裏。 – 4castle