root of a binary tree. Write the tree as a single string by these rules (visiting node, then left subtree, then right subtree):
- a node is written as its value;
- if a node has children, its value is followed by the left subtree in brackets and then the right subtree in brackets;
- empty bracket pairs () are left out, with one exception: when the left child is missing but the right one exists, the empty pair () must stay in the left child's place, otherwise the right child could not be told apart from a left one.
So a leaf gets no brackets at all, and a node with only a left child gets a single pair.root=tree_node([7, -2, 5, None, None, 1]) → '7(-2)(5(1))'
-2 has no children, so it is written as just -2. 5 has only a left child, so it becomes 5(1) with no empty brackets on the right. Result: 7(-2)(5(1)).
root=tree_node([4, None, 9, 8]) → '4()(9(8))'
4 has no left child but does have a right one, so an empty pair () is required: 4()(9(8)).
root=tree_node([3]) → '3'
root=tree_node([7, -2, 5, None, None, 1])
'7(-2)(5(1))'
Run checks the first 3 tests in your browser. Submit checks all 110 tests on the server, hidden ones included.