1. Expression Tree Construction and Post-Order Traversal
Intuition
Parse the infix string into a full binary expression tree by recursively splitting on the lowest precedence operator, then generate the postfix string via a post-order traversal (Left, Right, Root).
Algorithm
- Step 1: Find the main operator outside parentheses with lowest precedence.
- Step 2: Create a root tree node for this operator.
- Step 3: Recursively parse left substring as left child and right substring as right child.
- Step 4: Perform Post-Order traversal (
left -> right -> root) to produce postfix string.
#include <iostream>#include <string>#include <stack> class Solution { int precedence(char c) { if (c == '^') return 3; if (c == '*' || c == '/') return 2; if (c == '+' || c == '-') return 1; return -1; }public: std::string infixToPostfix(std::string s) { std::stack<char> st; std::string result = ""; for (char c : s) { if (isalnum(c)) { result += c; } else if (c == '(') { st.push(c); } else if (c == ')') { while (!st.empty() && st.top() != '(') { result += st.top(); st.pop(); } if (!st.empty()) st.pop(); } else { while (!st.empty() && (precedence(st.top()) > precedence(c) || (precedence(st.top()) == precedence(c) && c != '^'))) { result += st.top(); st.pop(); } st.push(c); } } while (!st.empty()) { result += st.top(); st.pop(); } return result; }}; int main() { Solution solver; std::cout << "Postfix: " << solver.infixToPostfix("(A+B)*(C+D)") << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Building an explicit Abstract Syntax Tree by searching minimum precedence root operators requires O(N2) recursive splitting. - Space complexity:
O(N)— O(N) tree nodes.
Why Brute Force Doesn't Scale:
A long flat expression like A+B+C+...+Z requires quadratic scans.
Shunting Yard algorithm processes 100,000 characters in <15ms.