Problem 926
Construct String from Binary Tree
Easy · 10 pts · Tree, String, Depth-First Search
Problem
Write a binary tree as a string in preorder: the node's value, then its left subtree in parentheses, then its right subtree in parentheses. Leave out empty parentheses when they are not needed: a node with no children has no parentheses, and a missing right child is simply omitted. But when a node has a right child and no left child, keep () for the missing left child, so the string still describes the tree uniquely.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the string representation of the tree.
Constraints
1 <= number of nodes <= 10000; -1000 <= value <= 1000
Example input
5 1 2 3 null 4
Example output
1(2()(4))(3)
Explanation
For 1 2 3 null 4, node 2 has no left child but a right child 4, so it is written 2()(4). The whole tree becomes 1(2()(4))(3).