Skip to content

Latest commit

 

History

History
29 lines (26 loc) · 826 Bytes

606.md

File metadata and controls

29 lines (26 loc) · 826 Bytes

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)