Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to visually print a NON binary tree?

Tags:

java

tree

I made a basic tree where all the nodes have a name and a set of children.

public class Tree {
    String data;
    Tree parent = null;
    HashSet children = new HashSet();

    public Tree(String nodeName) {
        this.data = nodeName;
    }

    public void parent(Tree parent) {
        this.parent = parent
    }

    public void addAChild(Tree child) {
        this.children.add(child);
        child.parent(this);
    }

And to use this class

Tree a = new Tree("root");
Tree b = new Tree("n1");
Tree c = new Tree("n2");
Tree d = new Tree("n3");
Tree e = new Tree("n4");
Tree f = new Tree("n5");

a.addAChild(b);
a.addAChild(c);
a.addAChild(d);

d.addAChild(e);
e.addAChild(f);

This makes sense to me but I'd like a visual representation of the tree so that I can quickly test to see if the children and nodes are in the right place.

I'm trying to make the output look like this:enter image description here

Or something similar.

like image 733
Ryan Smith Avatar asked Mar 24 '26 16:03

Ryan Smith


1 Answers

A quick and dirty way of printing the tree would involve adding a method like this to your Tree class:

public void print(int level) {
    for (int i = 1; i < level; i++) {
        System.out.print("\t");
    }
    System.out.println(data);
    for (Tree child : children) {
        child.print(level + 1);
    }
}

level represents the level of the node in the tree, which is defined as 1 + (the number of connections between the node and the root). It dictates how much the node will be indented in the output.

Then you can print the tree by printing the root (the level of the root is 1):

a.print(1);

Getting output like this:

root
    n1
    n2
    n3
        n4
            n5
like image 185
Cinnam Avatar answered Mar 27 '26 06:03

Cinnam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!