Problem statement

https://leetcode.com/problems/binary-tree-paths/

Solution

Have auxiliary function, which returns for the node current path. Traverse tree and add path to result if we see a leaf.

Complexity

Time and space complexity can be potentially O(n^2) for tree of height n.

Code

class Solution:
    def binaryTreePaths(self, root):
        def dfs(node, path): 
            if not node.left and not node.right: self.ans.append(path)   
            if node.left: dfs(node.left, path + "->" + str(node.left.val))
            if node.right: dfs(node.right, path + "->" + str(node.right.val))      

        self.ans = []
        dfs(root, str(root.val))
        return self.ans