Construct String From Binary Tree Problem
Description
LeetCode Problem 606.
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
Input: root = [1,2,3,4]
Output: "1(2(4))(3)"
Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)"
Example 2:
Input: root = [1,2,3,null,4]
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
Constraints:
- The number of nodes in the tree is in the range [1, 10^4].
- -1000 <= Node.val <= 1000
Solution
Approach: Preorder DFS with One Output Buffer
Write the tree in preorder: a node's value, then its left subtree in parentheses, then its right subtree in parentheses. The only question is which empty pairs () can be dropped while the string still describes exactly one tree.
- Leaf: write just the value, with no parentheses at all.
- Only a left child: write
val(left). Dropping the empty right pair is safe, because a single pair after a value always means the left child. - A right child (with or without a left one): write
val(left)(right), and keep the left pair even when the left child is missing, so it becomesval()(right). Without it,1()(2)(2 on the right) would turn into1(2), which means 2 on the left.
So the rule fits in two checks: open a left pair whenever the node is not a leaf, and open a right pair only when a right child exists.
Append every piece to one shared buffer (a list of strings, a StringBuilder, a strings.Builder) instead of returning and concatenating a new string at each node. Concatenating subtree strings copies the same characters again at every level, which costs O(n2) on a tall tree.
Complexity: O(n) time, where n is the number of nodes, and O(h) extra space for the recursion, where h is the height of the tree (the output itself is O(n)).
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
parts = [] # pieces of the answer, joined at the end
def write(node: TreeNode) -> None:
parts.append(str(node.val))
if node.left is None and node.right is None:
return
# The left pair stays even when empty if there is a right child,
# otherwise "1()(2)" and "1(2)" would look the same.
parts.append("(")
if node.left is not None:
write(node.left)
parts.append(")")
if node.right is not None:
parts.append("(")
write(node.right)
parts.append(")")
write(root)
return "".join(parts)