#606
Construct String from Binary Tree
MediumStringTreeDepth-First SearchBinary TreeDepth-First SearchRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a recursive approach similar to the brute force method but avoids unnecessary string concatenations by building the string in a more efficient manner. This ensures we only traverse the tree once and construct the string in linear time.
⚙️
Algorithm
4 steps- 1Step 1: Define a recursive function that takes a node and builds the string.
- 2Step 2: Append the node's value to the result string.
- 3Step 3: If the node has a left child, append its value enclosed in parentheses.
- 4Step 4: If the node has a right child, check if the left child is absent and append empty parentheses if so, then append the right child's value in parentheses.
solution.py9 lines
1def tree2str(root):
2 if not root:
3 return ""
4 result = str(root.val)
5 if root.left or root.right:
6 result += f'({tree2str(root.left)})'
7 if root.right:
8 result += f'({tree2str(root.right)})' if root.left or root.right else ''
9 return resultℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the recursive call stack and the space used for the resulting string.
- 1Understanding how to represent tree structures in strings is crucial for many coding problems.
- 2Recognizing when to include or omit parentheses based on child presence is key to solving this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.