Construct an expression tree from a given postfix notation and print the infix notation.

The binary expression tree is a binary tree whose leaves are operands, such as constants or variable names, and the other nodes contain operators.

For example, the postfix notation a b + c d e + * * results in the following expression tree. The corresponding infix notation is (a+b)*(c*(d+e)) which can be produced by traversing the expression tree in an inorder fashion. However, an opening and closing parenthesis must be added at the beginning and end of each expression (every subtree represents a subexpression).

Expression Tree

Practice this problem

The construction of the expression tree takes place by reading the postfix expression one symbol at a time. If the symbol is an operand, a new binary tree node is created, and its pointer is pushed onto a stack. If the symbol is an operator, the pointers to two trees, x and y, are popped from the stack, and a new tree whose root is the operator and whose left and right children point to y and x, respectively is formed. A pointer to this new tree is then pushed to the stack. In the end, a pointer to the full expression tree remains on the stack.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Postfix Expression: ab+cde+**
Infix Expression: ((a+b)*(c*(d+e)))

Java


Download  Run Code

Output:

Postfix Expression: ab+cde+**
Infix Expression: ((a+b)*(c*(d+e)))

Python


Download  Run Code

Output:

Postfix Expression: ab+cde+**
Infix Expression: ((a+b)*(c*(d+e)))

The time complexity of the above solution is O(n) and requires O(n) extra space for the stack, where n is the length of the postfix expression.