Construct String From Binary Tree

Medium Topics Company Tags

Represent the binary tree as a string by writing each node's value before its children. Enclose each child's representation in parentheses, with the left child before the right child.

A leaf contributes only its value. If a node has only a left child, omit the missing right child entirely. If it has only a right child, write () for the missing left child before the right child's parentheses. These rules preserve the tree's structure while removing unnecessary empty parentheses.

Examples use level-order arrays. After the root, each present node contributes left and right child entries in queue order. null marks a missing child, and trailing missing entries may be omitted.

Example 1:

Construct String from Binary Tree, example 1: illustration of the example

Input: root = [7,2,9,null,4]

Output: "7(2()(4))(9)"

Explanation: The left subtree is 2()(4): its missing left child needs an empty pair before its right child. Enclosing both root subtrees produces 7(2()(4))(9).

Example 2:

Construct String from Binary Tree, example 2: illustration of the example

Input: root = [-3,null,6]

Output: "-3()(6)"

Explanation: The root has a right child but no left child. The empty pair in -3()(6) preserves that distinction.

Example 3:

Construct String from Binary Tree, example 3: illustration of the example

Input: root = [5,0]

Output: "5(0)"

Explanation: The root has only a left child, so 5(0) is sufficient. No empty pair is needed for the missing right child, and the leaf 0 has no child parentheses.

Constraints:

  • The tree contains between 1 and 10000 nodes.
  • -1000 <= Node.val <= 1000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.