简体   繁体   English

级别顺序树打印中的Java缩进,而不是二叉树

[英]Java indentation in Level-order Tree print, not binary tree

I want to print my non-binary tree with level-order traverse. 我想用级别顺序遍历打印我的非二叉树。 In the code below I indent every time a new set of children has been added, but somehow I need to remove indentations when I go back in the tree again. 在下面的代码中,每次添加一组新的子代时我都会缩进,但是当我再次回到树中时,我需要以某种方式删除缩进。 Here's how this tree prints: 这棵树的打印方式如下:

Root
  Home
    HomeChild1
    HomeChild2
    Documents (should be same level as Home)
      DocumentChild1
      DocumentChild2
      Downloads (should be same level as Home and Documents)
        DownloadsChild1

Code: 码:

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++;
            }
        }

Here is what I want it to look like 这是我想要的样子

Root
  Home
    HomeChild1
    HomeChild2
  Documents
    DocumentChild1
    DocumentChild2
  Downloads
    DownloadsChild1

You need to increment the indent when you start processing children, and then decrement it when you reach the end of a group of children. 开始处理子代时,您需要增加缩进量,而当到达一组子代的末尾时,则需要减少缩进量。

You would be better off doing this whole thing using something like a recursive call rather than the queue though. 您最好使用递归调用而不是队列来完成整个事情。 The queue is adding a lot of complexity and not helping. 队列增加了很多复杂性,无济于事。

Something like: 就像是:

recurseTree(Thing obj, String indent) {
    print(indent+obj.value);
    if (obj.children != null) {
       for (Thing child: obj.children) {
          recurseTree(child, indent+"   ");
       }
    }
}

You could make some optimisations here (for example only doing the string concatonation once) and you will need to do a bit of tidying up but that should give you the basic framework you need. 您可以在此处进行一些优化(例如,只进行一次字符串合并),并且需要进行一些整理,但这应该为您提供所需的基本框架。

Start it using 使用开始

recurseTree(root, "");

You never reset your indent value. 您永远不会重置缩进值。 You need to copy its value so you can restore it after you went through a group of children 您需要复制其值,以便在经历一组儿童后可以恢复它的值

Btw, if you try something recursive it's way easier to handle. 顺便说一句,如果您尝试递归操作,则更容易处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM