我想打印具有级别顺序遍历的非二叉树。在下面的代码中,每次添加一组新的子元素时,都会缩进,但当我再次返回树时,我需要删除缩进。以下是这棵树打印:级别顺序中的Java缩进树打印,而不是二叉树
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广度优先算法时找不到递归解决方案xD –
@SimonAndersson这是递归的经典用例之一,所以我很惊讶没有出现。 –
是的,但深度优先更常见,也许这就是为什么 –