有一个这样的结构:
public class TreeNode {
private String key;
private List<TreeNode> children;
....
}
我重写了 toString() 函数
@Override
public String toString() {
String treeStructure = "TreeNode [key=" + key + "]";
if(children!=null){
for(TreeNode child:children){
treeStructure = treeStructure+"--- >"+children.toString()+"/n";
}
}
return treeStructure;
}
然后我测试结果:
public static void main(String[] args) {
TreeNode node = new TreeNode();
node.setKey("root");
List<TreeNode> children = new ArrayList<TreeNode>();
TreeNode child1 = new TreeNode();
child1.setKey("child1");
TreeNode child2 = new TreeNode();
child2.setKey("child2");
children.add(child1);
children.add(child2);
List<TreeNode> grandchildren = new ArrayList<TreeNode>();
TreeNode grandchild = new TreeNode();
grandchild.setKey("grandchild");
grandchildren.add(grandchild);
node.setChildren(children);
child1.setChildren(grandchildren);
System.out.println(node);
}
但是当我运行它时,输出是:
TreeNode [key=root]--->[TreeNode [key=child1]--->[TreeNode [key=grandchild]]/n, TreeNode [key=child2]]/n--->[TreeNode [key=child1]--->[TreeNode [key=grandchild]]/n, TreeNode [key=child2]]/n
如何在输出中添加换行符,如下所示:
TreeNode [key=root]--->TreeNode [key=child1]--->TreeNode [key=grandchild]
--->TreeNode [key=child2]
但是现在 child1 显示了两次,并且结果中没有添加换行符。
================================我改了函数:</p>
@Override
public String toString() {
String treeStructure = "TreeNode [key=" + key + "]";
if(children!=null){
for(TreeNode child:children){
treeStructure = treeStructure+"\n"+"-->"+children.toString()+"\n";
}
}
return treeStructure;
}
那么输出是:
TreeNode [key=root]
--->[TreeNode [key=child1]
--->[TreeNode [key=grandchild]]
, TreeNode [key=child2]]
--->[TreeNode [key=child1]
--->[TreeNode [key=grandchild]]
, TreeNode [key=child2]]
为什么孩子重复了两次,“,”从哪里来?