0

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);
}

1 Answer 1

1

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); 
} 
Sign up to request clarification or add additional context in comments.

2 Comments

The links you provided are useful, but one of them is C++ based and the other PHP, none of them has something to do with Java. Unless you extract the basic ideas, your answer might not help the OP at all.
@aka-one and Zoe I thought of adding comment just below the question, but it seems I do not have enough reputation to do that, so thought of answering/pointing to useful resources.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.