How can you print a tree in a beautifully formatted way?

What is the easiest way to print a tree in a tree structure? Such as...

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

Even formatting manually. How can you make a program print a tree this way?

+5
source share
6 answers

If there is some good graphics library that you can use, you will have many problems representing the hierarchy in the form in which you are describing.

, , , . , line-wrap?

, .

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

linewrap - . .

, 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.
    }
}

,

+5

, - PHP var_dump - var_dump , , :

root {
    child1 {
        anotherchild
    }
    child2
    child3 {
        yup
        another
    }
}
0
0

? ASCII-art.

, , , ?

0

, . java- , , Google- , .

This is just a recursive algorithm that adjusts the position of the parent node based on the child nodes. In pseudo code, it is something like this:

positionNode (node,x,y) {
    foreach (child in node.children) {
        positionNode(child,x,y+1)
        x ++
    }
    node.x = (x-1)/2
    node.y = y
}

Maybe I don’t remember it right, you may need to change the code a bit so that everything is correct.

0
source

The following answer is in java, but it is so simple that it can be easily rewritten into other languages:

public interface Function1<R, T1>
{
    R invoke( T1 argument1 );
}

public interface Procedure1<T1>
{
    void invoke( T1 argument1 );
}

public static <T> void dump( T node, Function1<List<T>,T> breeder,
       Function1<String,T> stringizer, Procedure1<String> emitter )
{
    emitter.invoke( stringizer.invoke( node ) );
    dumpRecursive( node, "", breeder, stringizer, emitter );
}

private static final String[][] PREFIXES = { { " β”œβ”€ ", " β”‚  " }, { " └─ ", "    " } };

private static <T> void dumpRecursive( T node, String parentPrefix,
        Function1<List<T>,T> breeder, Function1<String,T> stringizer,
        Procedure1<String> emitter )
{
    for( Iterator<T> iterator = breeder.invoke( node ).iterator(); iterator.hasNext(); )
    {
        T childNode = iterator.next();
        String[] prefixes = PREFIXES[iterator.hasNext()? 0 : 1];
        emitter.invoke( parentPrefix + prefixes[0] + stringizer.invoke( childNode ) );
        dumpRecursive( childNode, parentPrefix + prefixes[1], breeder, stringizer, emitter );
    }
}

He produces the following conclusion:

Automobile
 β”œβ”€ Passenger Vehicle
 β”‚   β”œβ”€ Light Passenger Vehicle
 β”‚   β”‚   β”œβ”€ Two Wheeled
 β”‚   β”‚   β”‚   β”œβ”€ Moped
 β”‚   β”‚   β”‚   β”œβ”€ Scooter
 β”‚   β”‚   β”‚   └─ Motorcycle
 β”‚   β”‚   β”œβ”€ Three Wheeled
 β”‚   β”‚   └─ Four Wheeled
 β”‚   β”‚       β”œβ”€ Car
 β”‚   β”‚       β”œβ”€ Station Wagon
 β”‚   β”‚       β”œβ”€ Pick-up Truck
 β”‚   β”‚       └─ Sports Utility Vehicle
 β”‚   └─ Heavy Passenger Vehicle
 β”‚       β”œβ”€ Bus
 β”‚       β”‚   β”œβ”€ Single-Deck Bus
 β”‚       β”‚   β”‚   β”œβ”€ Mini Bus
 β”‚       β”‚   β”‚   └─ Big Bus
 β”‚       β”‚   └─ Double-Deck Bus
 β”‚       └─ Coach
 β”‚           β”œβ”€ Deluxe
 β”‚           └─ Air-Conditioned
 └─ Goods Vehicle
     β”œβ”€ Light Goods Vehicle
     β”‚   β”œβ”€ Delivery Van
     β”‚   β”œβ”€ Light Truck
     β”‚   └─ Tempo
     β”‚       β”œβ”€ Three Wheeler Tempo
     β”‚       └─ Four Wheeler Tempo
     └─ Heavy Goods Vehicle
         β”œβ”€ Truck
         └─ Tractor Trailer

... if you call it using the following sample program:

final class Scratch
{
    static class Node
    {
        String name;
        List<Node> children;

        Node( String name, Node... children )
        {
            this.name = name;
            this.children = Arrays.asList( children );
        }
    }

    public static void main( String[] args )
    {
        Node tree = new Node( "Automobile",
                new Node( "Passenger Vehicle",
                        new Node( "Light Passenger Vehicle",
                                new Node( "Two Wheeled",
                                        new Node( "Moped" ),
                                        new Node( "Scooter" ),
                                        new Node( "Motorcycle" ) ),
                                new Node( "Three Wheeled" ),
                                new Node( "Four Wheeled",
                                        new Node( "Car" ),
                                        new Node( "Station Wagon" ),
                                        new Node( "Pick-up Truck" ),
                                        new Node( "Sports Utility Vehicle" ) ) ),
                        new Node( "Heavy Passenger Vehicle",
                                new Node( "Bus",
                                        new Node( "Single-Deck Bus",
                                                new Node( "Mini Bus" ),
                                                new Node( "Big Bus" ) ),
                                        new Node( "Double-Deck Bus" ) ),
                                new Node( "Coach",
                                        new Node( "Deluxe" ),
                                        new Node( "Air-Conditioned" ) ) ) ),
                new Node( "Goods Vehicle",
                        new Node( "Light Goods Vehicle",
                                new Node( "Delivery Van" ),
                                new Node( "Light Truck" ),
                                new Node( "Tempo",
                                        new Node( "Three Wheeler Tempo" ),
                                        new Node( "Four Wheeler Tempo" ) ) ),
                        new Node( "Heavy Goods Vehicle",
                                new Node( "Truck" ),
                                new Node( "Tractor Trailer" ) ) ) );
        dump( tree, n -> n.children, n -> n.name, s -> System.out.println( s ) );
    }
}
0
source

All Articles