2

I've been trying to switch over to Java from Node and one thing I'm wondering about is how to print an object such as a binary Tree in a similar format to how node would display it. For instance, my binary tree initiation code is as follows:

public class BinaryTree {
    int data;
    BinaryTree left, right;

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree(1);
        tree= new BinaryTree(1);
        tree.left = new BinaryTree(2);
        tree.right= new BinaryTree(3);
        tree.left.right = new BinaryTree(4);
        System.out.println(tree); // output -> BinaryTree@4554617c
    }

    public BinaryTree(int data) {
      super();
      int val;
      this.left = this.right = null;
  }
}

In node, this binary tree would be displayed as the following:

TreeNode {
  val: 1,
  right: TreeNode { val: 3, right: null, left: null },
  left:
   TreeNode {
     val: 2,
     right: TreeNode { val: 4, right: null, left: null },
     left: null } }

However in Java, when I do System.out.println(tree);

the output -> BinaryTree@4554617c

What is the proper way to print my BinaryTree and what's a good way to do this? Is there a way to print the tree in a JSON format?

user10109
  • 121
  • 1
  • 3
  • 9
  • Of course to use `System.out.println(tree);`, you must override the `toString()` method in your class, otherwise the default implementation will used... – 0x1C1B Apr 28 '18 at 15:21
  • Java call `toString` on your tree. So what you need is a custom implementation of the `toString()` method. Check out the JavaDocs. Printing recursive structures via toString can be a bit problematic at times so I usually prefer a separate method that just prints the structure for the instance passed. – Dennis Hunziker Apr 28 '18 at 15:22
  • Is there an short easy way to do this? – user10109 Apr 28 '18 at 15:25
  • Yes, there is: write a simple method that iterates over the nodes recursively. – jahroy Apr 28 '18 at 15:27
  • There's no built in method to display it in JSON format? I have to build an entire method to do this? – user10109 Apr 28 '18 at 15:29
  • https://vanya.jp.net/vtree/ – humble_wolf Feb 05 '20 at 19:35

2 Answers2

1

Printing tree will give you the memory address of the main tree node. If you want to print the content of the tree, you will need to implement a recursive print method and recurse over each node in the tree.
If the node is a final node (no right or left tree) print the content of that node. Otherwise move down the tree. You can print on the way down the tree or on the way back depending on how you want the tree to look.
I hope I understood the question correctly.

  • I'm used to JSON format so I was hoping for something similar to Node I suppose, not so much just printing numbers out. i.e.) TreeNode { val: 1, right: TreeNode { val: 3, right: null, left: null }, left: TreeNode { val: 2, right: TreeNode { val: 4, right: null, left: null }, left: null } } – user10109 Apr 28 '18 at 15:35
  • Ok. You can make it print like that with a recursive function. If you know the shape and size and that it won't change, you could write a static function to print the tree, instead of using recursion. – Josh Thrasher Apr 28 '18 at 15:53
1

I found this solution on stack overflow and modified it...

public static class TreeNode
{
    int value;
    TreeNode leftChildren;
    TreeNode rightChildren;

    public TreeNode(int value, TreeNode left, TreeNode right)
    {
        this.value = value;
        this.leftChildren = left;
        this.rightChildren = right;
    }

    public addLeftNode(TreeNode node)
    {
        this.leftChildren = node;
    }

    public addRightNode(TreeNode node)
    {
        this.rightChildren = node;
    }

    public void print(String prefix)
    {
        print(prefix, true);
    }

    private void print(String prefix, boolean isTail)
    {
        System.out.println(prefix + (isTail ? "└── " : "├── ") + this.toString());

        if(null != leftChildren)
        {
            leftChildren.print(prefix + (isTail ? "    " : "│   "), (null == rightChildren ? true : false));
        }

        if(null != rightChildren)
        {
            rightChildren.print(prefix + (isTail ?"    " : "│   "), true);
        }

    }

    @Override public String toString()
    {
        return "TreeNode { Value: " + this.value + "}";
    }
}

The first node represents the left and the second node the right node in th binary tree.

EDIT: You can use this like this:

TreeNode root = new TreeNode(22, null, null);

root.addLeftNode(new TreeNode(15, null, null));
root.addRightNode(new TreeNode(35, new TreeNode(27, null, null), null));

root.print(); // This will print recursively all sub-nodes

Alternate you can write a wrapper class like this:

public class BinaryTree
{
    private TreeNode root;

    // implementation of getters and setters

    public void print()
    {
        this.root.print();
    }
}
0x1C1B
  • 1,204
  • 11
  • 40
  • How would you use this method with my example? – user10109 Apr 28 '18 at 16:33
  • I added a short example for the usage of this class... Just use the print method like in my provided class,just paste the method in your own class, it should work – 0x1C1B Apr 28 '18 at 17:05