concise Python DFS recursion


  • 0
    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            path = []
            re = []
            def dfs(node):
                if node:
                    path.append(str(node.val))
                    dfs(node.left)
                    dfs(node.right)
                    if not node.left and not node.right:
                        re.append(reduce(lambda x, y: x + "->" + y, path))
                    path.pop()
            dfs(root)
            return re
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.