Reputation:
I am having trouble with writing this section of my code into a tree format. I want it to output as
x
x x
x x
but it is outputting as
x
x
x
....
How would I be able to add indentations and spaces in my code? And in the case of an empty node, enter an asterisk or any symbol?
public void insert(int value)
{
Node n = new Node(value);
if(root == null)
root = n;
else
{
Node parent = root;
while(parent != null)
{
if(value < parent.data)
{
if(parent.left == null)
{
parent.left = n;
return;
}
else
{
parent = parent.left;
}
}
else
{
if(parent.right == null)
{
parent.right = n;
return;
}
else
{
parent = parent.right;
}
}
}
}
}
private void inOrder(Node n)
{
if(n == null)
return;
inOrder(n.left);
System.out.println(n.data + " ");
inOrder(n.right);
}
public void printInorder()
{
inOrder(root);
}
Upvotes: 0
Views: 380
Reputation: 574
please check this Print a binary tree in a pretty way (or) You can check as well this link https://www.geeksforgeeks.org/print-binary-tree-2-dimensions in which it prints the tree in left to right order instead of top to bottom, the equivalent java code would be as follows where on passing root value as Tree's root node and space as 0.
void print2DUtil(Node root, int space)
{
// Base case
if (root == NULL)
return;
// Increase distance between levels
space += COUNT;
// Process right child first
print2DUtil(root.right, space);
// Print current node after space
// count
printf("\n");
for (int i = COUNT; i < space; i++)
printf(" ");
printf("%d\n", root.data);
// Process left child
print2DUtil(root.left, space);
}
Upvotes: 1