SDE & MLE Prep

257. Binary Tree Paths

Problem

Return every root-to-leaf path of a binary tree as a string of values joined by "->", in any order.

Example: [1,2,3,null,5] → ["1->2->5","1->3"]

DFS with the path so far; at a leaf, join it with ->.

Complexity: O(n · h).

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []

        def dfs(node, path):
            if not node:
                return
            path = path + [str(node.val)]
            if not node.left and not node.right:
                res.append("->".join(path))
            dfs(node.left, path)
            dfs(node.right, path)

        dfs(root, [])
        return res