Prefix to postfix (2 solutions) – stack and recursion

In mathematics expressions, there are infix, prefix and postfix notations. Infix notation is characterized by the placement of operators between operands. For example, the plus sign in 2 + 2. Prefix notation is a notation in which operators precede their operands, such as + 3 4. Postfix notation is a notation in which operators follow their operands, for example 3 4 +. This post introduces how to convert an expression from prefix to postfix. There are two methods, stack and recursion. We use letters as operands in the expression.

How to convert prefix to postfix using a stack?

A common method for converting a prefix expression to postfix is by using a stack. Starting from the end of the prefix expression, we scan each character one by one. If the character is an operand (e.g., a letter), we push it onto the stack. If it’s an operator (such as +, –, , or /), we pop the top two operands from the stack, combine them with the operator in postfix order (operand1 operand2 operator), and push the resulting sub-expression back onto the stack. Once the scan is complete, the top of the stack holds the final postfix expression.

How to convert prefix to postfix using recursion?

An alternative approach is to use recursion. In this method, we process the prefix expression from the beginning. Since a prefix expression starts with an operator, we first remove the first character and store it in a variable, op. Then, we recursively call the function twice to obtain the next two operands, stored as op1 and op2. After that, we create a list to build a postfix sub-expression by appending op1, op2, and then op in that order. When the recursion unwinds, the final list contains the complete postfix expression.

Google Interview Question

convert Prefix_to_Postfix using recursion
+ * A B / C D -> A B * C D / +

Java

JavaScript

Python

Output:
prefix: +*AB/CD
postfix(stack): AB*CD/+
postfix(recursion): AB*CD/+

O Notation:
Time complexity: O(n)
Space complexity: O(n)


Download PrefixToPostfix.java
Download PrefixToPostfix.js
Download PrefixToPostfix.py
Covert prefix to postfix using stack or recursion (YouTube)
Java Coding Interview Pocket Book

Comments are closed