Javaで「最初の子の次の兄弟」ツリーのクラスを実装しました。
ここにそのようなツリーを表すリンクがあります
http://www.cs.utexas.edu/~novak/cs315116.html
以下の機能を実装しました。
addChild();
getLabel();
setLabel(T v);
getParent();
getNextSibling();
getFirstChild();
私の addChild 関数は、次の順序で子を追加します。
public void addChild(Tree<T> c) {
c.parent = this;
if (firstChild == null)
firstChild = c;
else {
c.nextSibling = firstChild;
firstChild = c;
}
}
That is, if we have a tree node 1 and we add tree node 2 and then tree node 3 to it then the final tree would be,
1.addChild(2);
1.addChild(3);
1 1
/ \ which is internally stored as /
3 2 3 - 2
The most recent child added would be the first child
そのようなツリーを引数として指定すると、ツリーのコピーを作成して返す CopyTree 関数を実装したいと考えています。初期コードはいくつかありますが、正しい再帰を取得できません。
private Tree<String> CopyTree(Tree<String> tr){
if (tr == null)
return null;
Tree<String> t = new Tree<String>();
t.setLabel(tr.getLabel());
if (tr.getFirstChild() != null) {
t.addChild(CopyTree(tr.getFirstChild()));
}
Tree<String> temp = tr.left();
if (temp != null) {
while (temp.getNextSibling() != null) {
t.addChild(CopyTree(temp.getNextSibling()));
temp = temp.getNextSibling();
}
}
return t;
}
再帰を機能させるために何をすべきか??
前もって感謝します