606. Construct String from Binary Tree
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 70% Topics: String, Tree, Depth-First Search, Binary Tree
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(h)
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if not t: return ""
s = str(t.val)
if t.left or t.right:
s += "(" + self.tree2str(t.left) + ")"
if t.right:
s += "(" + self.tree2str(t.right) + ")"
return s
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions