Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you print out a tree in a nicely formatted way?

What is the easiest way to print out a tree in it's tree-structure? Such as...

                  some root
              /     |         \
          child1   child2     child 3
           /
      anotherchild               / \
                             yup     another

Even formatting it by hand is hard. How can you make a program print a tree this way?

like image 903
oldspice Avatar asked Nov 15 '10 01:11

oldspice


People also ask

How do you print a binary tree from a tree?

You start traversing from the root, then go to the left node, then you again go to the left node until you reach a leaf node. At that point in time, you print the value of the node or mark it as visited and move to the right subtree. Continue the same algorithm until all nodes of the binary tree are visited.


1 Answers

Unless there is some nice graphical library that you can use, you will have a lot of trouble representing a hierarchy in the way that you describe.

Assuming you want to print it to the Console, or a file, you will have to contend with pre-calculating the lengths of all of the data elements in the entire tree in order to line them up correctly. And how do you handle things like line-wrap?

A much better way is to represent the tree vertically, using indentation to show a child element.

Root
    - Child1
        - Grandchild1
        - Grandchild2
    - Child2
        - Grandchild3
        - Grandchild4

This is much simpler to code, and more tolerant of things like linewrap - as there is only ever one element on a line. This is how a folder-browser or xml document might display its hierarchical data.

To do it this way, you do a depth-first traversal and before the recursive step you print out the node:

public void PrintNode(TreeNode node)
{
    PrintNode(node, 0);
}

private void PrintNode(TreeNode node, int indentation)
{
    // Print the value to the console/file/whatever
    // This prefixes the value with the necessary amount of indentation
    Print(node.Value, indentation);

    // Recursively call the child nodes.
    foreach(TreeNode childNode in node.Children)
    {
        PrintNode(childNode, indentation + 1); // Increment the indentation counter.
    }
}

Hope that helps

like image 143
sheikhjabootie Avatar answered Sep 30 '22 17:09

sheikhjabootie