Binary Tree to String Serialization (Custom Format)
Write a function to convert a binary tree into a specific string representation using pre-order traversal. The format must follow a nested parenthesis structure: (root, left_subtree, right_subtree). If a node is a leaf (or if a child is missing), the format should adapt accordingly based on the provided examples.
Given the following binary tree structure:
1
/ \
2 3
/ / \
4 5 6
/
7
- Input:
root = [1, 2, 3, 4, null, 5, 6, null, null, 7] - Expected Output:
"(1,(2,4,),(3,(5,7,),6))"
Explanation based on structure:
- Node 2’s subtree is
(2,4,)where 4 is the left child and the right child is empty. - Node 5’s subtree is
(5,7,). - Node 3’s subtree is
(3,(5,7,),6). - The entire tree wraps into the root 1.
Reconstructed from interview notes.