Problem Description
Given the root of a binary tree, construct a string consisting of the node values and parentheses by performing a preorder traversal. For each node, represent its value and, if necessary, its children inside parentheses. Omit unnecessary empty parentheses except when a node has a right child but no left child—in that case, include empty parentheses to indicate the missing left child.
Key Insights
- Use a recursive preorder traversal to visit nodes.
- For each node, include the value directly.
- If the node has a left child, include its string representation wrapped in parentheses.
- If the node does not have a left child but has a right child, include empty parentheses to maintain the structure.
- If a node has only a right child, include the left placeholder and then the right child’s representation in its own parentheses.
- This approach guarantees a one-to-one mapping between the string and the tree.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes, since each node is visited once. Space Complexity: O(n) in the worst case for the recursive call stack (unbalanced tree) and the string being constructed.
Solution
We solve the problem using recursion. The main idea is to perform a preorder traversal, processing each node as follows:
- Start with the node value as a string.
- Recursively obtain the string for the left child. If the left child is missing but a right child exists, append empty parentheses "()" to indicate the absence of the left subtree.
- Recursively obtain the string for the right child and append it in parentheses.
- Return the constructed string. This method correctly maintains the necessary structure and omits redundant parentheses.