0

I am trying to print out a binary tree using in-order traversal (in java), but without any ambiguity.

I created the tree from a post-order notation input.

For example, input = 2 3 4 * - 5 + I then create the tree, and want to print it out using in-order traversal.

So output must be = 2 - (3*4) + 5 However, using using in-order traversal obviously doesn't give me the separating brackets.

My question is, can I print the output the way I want, without meddling with the basic BinaryNode and BinaryTree classes, but only changing my driver class? And if so, how would I go about doing this?

If I can only do this by changing my printInOrder method (in the BinaryNode class), this is what it looks like so far :

public void printInOrder()
    {
        if (left != null)
        {
            left.printInOrder();            // Left
        }
        System.out.print(element);       // Node
        if (right != null)
        {
            right.printInOrder();           // Right
        }
    }

This is my first time on Stack Overflow, go easy on me if I didn't post correctly :)

1 Answers1

0

I figured it out, so for example, an input of 23+4+5* will give an output of (((2+3)+4)*5)

See code below:

//NOTE: printInOrder has been modified to exclude ambiguity
public void printInOrder()
{
    if (left != null)
    {
        if (height(left)== 0)
        {
            //when we reache the bottom of a node, we put a bracket around each side as we know this will have it's own operation
            // eg:  *
            //     / \
            //    3   4
            System.out.print("("); 
            left.printInOrder();            // Left
        }
        else
        {
            // We also put in a bracket here as this matches the closing brackets to come (which we do not know about yet)
            System.out.print("(");
           left.printInOrder();            // Left 
        }

    }
      System.out.print(element);                // Node
    if (right != null)
    {
        if (height(right) == 0)
        {
            //when we reache the bottom of a node, we put a bracket around each side as we know this will have it's own operation
            // eg:  *
            //     / \
            //    3   4
            right.printInOrder();           // Right
            System.out.print(")");
        }
        else
        {
            right.printInOrder();           // Right
           // System.out.print(")"); // this print statement actually isnt necessary
        }

    }
}