hi
so this code here as i test it on paper provides paranthesis on every leaf node, disregarding priority (operator precedence)

how can i make it add those paranthesis based on precedence of operators?

 void printInfix(Node n)
{   
    if (n == null)
    {
        if (n.isLeaf())//if n is a leaf, therefore a number
            System.out.print(n.element);
        else//n is not a leaf
        {
            System.out.print("(");
            printInfix(n.left);
            System.out.print(n.element);
            printInfix(n.right);
            System.out.print(")");
        }//end else
    }//end if   
} 

If we just take into account precedence (and not associativity), then all we need to know is the priority of the current operator as well as the one whose operand the current expression is. If the outer priority is higher than or equal to the inner one, we need parentheses. Otherwise we do not.

To implement this you can define a recursive helper method that takes the outer priority as an argument. The one-argument printInfix method would then only call the helper method with the priority 0 (0 because we don't want any parentheses around the outer expression).

Note that this does not remove the parentheses in (a + b) + c or a + (b + c) because those are about associativity rather than precedence. Handling that would be a bit more complicated.

i understand that logic, the problem is i dont know how to implement it in my code or code it

This article has been dead for over six months. Start a new discussion instead.