【发布时间】:2014-06-23 01:44:04
【问题描述】:
我试图弄清楚如何从下面给出的 parentheticRepresentation 类创建一个 toString() 方法。
public static <E> String parentheticRepresentation(Tree<E> T, Position<E> v) {
String s = v.element().toString();
if (T.islnternal(v)) {
Boolean firstTime = true;
for (Position<E> w : T.children(v))
if (firstTime) {
s += " ( " + parentheticRepresentation(T, w);
firstTime = false;
}
else s += ", " + parentheticRepresentation(T, w);
s += " ) ";
}
return s;
}
在我的主类中,当我为我的树创建节点并尝试输出整个树时,它只输出一个带有括号表示的节点。那么如何使用它创建另一个 toString() 类,以便当我调用输出我的树时,它会给我上面类中的表示。任何帮助将不胜感激!
public static void main(String[] args) {
LinkedTree<Character> T = new LinkedTree();
// add root
T.addRoot('A');
// add children of root
T.createNode('B', (TreeNode) (T.root()), new NodePositionList());
TreePosition C = T.createNode('C', (TreeNode) (T.root()),
new NodePositionList());
T.createNode('D', (TreeNode) (T.root()), new NodePositionList());
// add children of node C
T.createNode('E', C, new NodePositionList());
TreePosition F = T.createNode('F', C, new NodePositionList());
T.createNode('G', C, new NodePositionList());
// add childrn of Node F
T.createNode('H', F, new NodePositionList());
T.createNode('I', F, new NodePositionList());
// print out tree
System.out.println("Size = " + T.size());
System.out.println("Here is the tree:");
System.out.println(T);
}
}
【问题讨论】:
-
你期待像 A(B,C(E,F(H,I),G),D) 这样的东西吗?
-
是的。我只是不知道在我的 toString 方法中写什么,该方法使用括号表示返回我的输出。
标签: java data-structures tree linked-list