1. Unconditional Parentheses with Regex Replacement
Intuition
Output node.val(left)(right) for all nodes. Clean up empty () using string replacements.
When to apply: Basic baseline check.
Algorithm
- Step 1: Base recursion creates string with full parenthesis pairing.
- Step 2: Clean trailing empty parentheses where legal.
- Step 3: Return cleaned string.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: string tree2str(TreeNode* root) { if (!root) return ""; string left = tree2str(root->left); string right = tree2str(root->right); if (left.empty() && right.empty()) return to_string(root->val); if (right.empty()) return to_string(root->val) + "(" + left + ")"; return to_string(root->val) + "(" + left + ")(" + right + ")"; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n^2)— String manipulations and regex replacements create intermediate strings. - Space complexity:
O(n^2)— Regex matching copies strings repeatedly.