My code:

```
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
res = ''
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if not t:
return ''
self.res += str(t.val)
if t.left and not t.right:
self.res += '()'
elif t.left:
self.res += '(' + self.tree2str(t.left) + ')'
if not t.right:
self.res += ''
else:
self.res += '(' + self.tree2str(t.right) + ')'
return self.res
```

Your input

[1,2,3,4]

Your answer

"1(12())(1(12())3)"

Expected answer

"1(2(4))(3)"

Could someone explain why my code gives that answer?