Generate a String From Binary Tree Node Values

Problem Given the root of a binary tree, build a string that encodes its structure using node values and parentheses around each child subtree, in preorder. Omit unnecessary empty parentheses: a null right child produces nothing, but a null left child that has a non-null right sibling must still be shown as ().

Input / Output

  • Input: root of a binary tree.
  • Output: the encoded string.

Constraints

  • Preorder with parentheses; omit empty trailing parentheses but keep an explicit () for a missing left child when a right child exists.

Example

  • [1,2,3,null,4] → "1(2()(4))(3)" (node 2 has no left child but a right child 4, so its left is shown as ()).
added …
LeaderboardSalaryAccount