1. Recursive Expression Subtree Parsing
Intuition
Use recursive descent: an expression is either an operand or an operator followed by two valid subexpressions.
Algorithm
- Step 1: Track current index pointer in prefix string.
- Step 2: If current character is operand, return it.
- Step 3: If operator, recursively parse left child, then right child.
- Step 4: Return
"(" + left + op + right + ")".
#include <iostream>#include <string> class Solution { int idx = 0; std::string parse(const std::string& s) { char c = s[idx++]; if (isalnum(c)) { return std::string(1, c); } std::string left = parse(s); std::string right = parse(s); return "(" + left + c + right + ")"; }public: std::string preToInfix(std::string pre_exp) { idx = 0; return parse(pre_exp); }}; int main() { Solution solver; std::cout << "Infix: " << solver.preToInfix("*+AB-CD") << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Recursive top-down splitting constructs substrings taking O(N) per node across O(N) operations. - Space complexity:
O(N)— O(N) recursion call stack.
Why Brute Force Doesn't Scale:
Deep recursion risks call stack limits on long expressions.
Right-to-left stack processes 100,000 characters in <5ms.