0

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

2 Answers2

2

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, "");
Tim B
  • 40,716
  • 16
  • 83
  • 128
0

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.

rilent
  • 659
  • 1
  • 6
  • 22
  • First while loop, it adds all level 1 children to the queue, (home, documents,downloads). and next loop it removes home and add all homes children first in the queue, Im not sure where I need to reset the indent value – Simon Andersson May 03 '17 at 12:57
  • Tim B algorithm is simply the best to do what you are trying to achieve. – rilent May 03 '17 at 13:02