Java Level-order Tree 打印中的缩进,而不是二叉树
Java indentation in Level-order Tree print, not binary tree
我想用层序遍历打印我的非二叉树。在下面的代码中,每次添加一组新的子项时我都会缩进,但是当我再次返回树时我需要以某种方式删除缩进。这是这棵树的打印方式:
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
您永远不会重置缩进值。
您需要复制它的值,以便在经过一组 children
后恢复它
顺便说一句,如果你尝试递归的东西,它会更容易处理。
您需要在开始处理子项时增加缩进量,然后在处理完一组子项时减少缩进量。
你最好使用递归调用之类的东西而不是队列来完成整个事情。队列增加了很多复杂性并且没有帮助。
类似于:
recurseTree(Thing obj, String indent) {
print(indent+obj.value);
if (obj.children != null) {
for (Thing child: obj.children) {
recurseTree(child, indent+" ");
}
}
}
您可以在此处进行一些优化(例如只进行一次字符串连接),您需要做一些整理工作,但这应该会为您提供所需的基本框架。
开始使用
recurseTree(root, "");
我想用层序遍历打印我的非二叉树。在下面的代码中,每次添加一组新的子项时我都会缩进,但是当我再次返回树时我需要以某种方式删除缩进。这是这棵树的打印方式:
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
您永远不会重置缩进值。 您需要复制它的值,以便在经过一组 children
后恢复它顺便说一句,如果你尝试递归的东西,它会更容易处理。
您需要在开始处理子项时增加缩进量,然后在处理完一组子项时减少缩进量。
你最好使用递归调用之类的东西而不是队列来完成整个事情。队列增加了很多复杂性并且没有帮助。
类似于:
recurseTree(Thing obj, String indent) {
print(indent+obj.value);
if (obj.children != null) {
for (Thing child: obj.children) {
recurseTree(child, indent+" ");
}
}
}
您可以在此处进行一些优化(例如只进行一次字符串连接),您需要做一些整理工作,但这应该会为您提供所需的基本框架。
开始使用
recurseTree(root, "");