606. Construct String from Binary Tree Solution 1 (time O(n), space O(1)) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def tree2str(self, root): """ :type root: TreeNode :rtype: str """ def dfs(root): ans = str(root.val) if root.left is not None: ans = ans + "(" + dfs(root.left) + ")" if root.right is not None: if root.left is None: ans = ans + "()" ans = ans + "(" + dfs(root.right) + ")" return ans return dfs(root)