【发布时间】:2017-05-03 21:01:03
【问题描述】:
我想用级别顺序遍历打印我的非二叉树。在下面的代码中,每次添加一组新的孩子时我都会缩进,但是当我再次回到树中时,我需要以某种方式删除缩进。这是这棵树的打印方式:
Root
Home
HomeChild1
HomeChild2
Documents (should be same level as Home)
DocumentChild1
DocumentChild2
Downloads (should be same level as Home and Documents)
DownloadsChild1
代码:
queue.add(o); //root
int indent = 0;
while(!queue.isEmpty(){
for(int i=0; i<indent; i++){
print(" ");
}
Object tempObj = queue.remove(o);
print(tempObj.value);
if(tempObj.children != null){
//Adding all childrens, since its not a binary tree I loop throught all children
for(int i=0; i<tempObj.children.length; i++){
queue.add(0, tempObj.children[i];
}
indent++;
}
}
这是我想要的样子
Root
Home
HomeChild1
HomeChild2
Documents
DocumentChild1
DocumentChild2
Downloads
DownloadsChild1
【问题讨论】:
标签: java tree indentation traversal