简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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