Construct String from a Binary Tree (Leetcode 606)
Technique: FAITH technique of Recursion
Problem Link: https://leetcode.com/problems/construct-string-from-binary-tree/
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
def fun(root):
if(root is None):
return ""
l=fun(root.left)
r=fun(root.right)
if(l is not "" and r is not ""):
ans=str(root.val)+'('+l+')'+'('+r+')'
elif(l is "" and r is not ""):
ans=str(root.val)+'()'+'('+r+')'
elif(l is not "" and r is ""):
ans=str(root.val)+'('+l+')'
else:
ans=str(root.val)
return ans
return fun(root)
Last updated