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?