Construct String from Binary Tree - Problem
You need to construct a string representation of a binary tree following specific formatting rules based on preorder traversal.
The Rules:
- Each node is represented by its integer value
- If a node has children, wrap them in parentheses
() - Key rule: Omit empty parentheses
()EXCEPT when a node has a right child but no left child - then you MUST include()to show the missing left child
Examples:
- Node with left child only:
1(2) - Node with right child only:
1()(3)โ Notice the empty() - Node with both children:
1(2)(3)
This ensures a unique string representation that can be converted back to the original tree structure.
Input & Output
example_1.py โ Basic Tree with Both Children
$
Input:
root = [1,2,3,null,4]
โบ
Output:
"1(2()(4))(3)"
๐ก Note:
Node 1 has both children 2 and 3. Node 2 has only right child 4, so we need empty () for missing left child, resulting in ()(4). Node 3 has no children.
example_2.py โ Simple Tree
$
Input:
root = [1,2,3,4]
โบ
Output:
"1(2(4))(3)"
๐ก Note:
Node 1 has children 2 and 3. Node 2 has only left child 4, so no empty parentheses needed. Node 3 has no children.
example_3.py โ Single Node
$
Input:
root = [1]
โบ
Output:
"1"
๐ก Note:
Single node with no children requires no parentheses at all.
Visualization
Tap to expand
Understanding the Visualization
1
Start at Root
Begin with root node value and check for children
2
Process Left Subtree
Recursively convert left subtree to string
3
Handle Missing Left Child
Add empty () when right child exists but left doesn't
4
Process Right Subtree
Convert right subtree if it exists
5
Combine Results
Assemble final string with proper parentheses
Key Takeaway
๐ฏ Key Insight: The empty parentheses () act as placeholders to maintain the left-right child order, ensuring the string can be uniquely converted back to the original tree structure.
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once in the tree
โ Linear Growth
Space Complexity
O(n)
Recursion stack depth equals tree height, plus string storage
โก Linearithmic Space
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -1000 โค Node.val โค 1000
- Tree is guaranteed to be a valid binary tree
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code