Leetcode 257 Solution

This article provides solution to leetcode question 257 (binary-tree-paths)

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

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        ans = []

        def dfs(node, paths):
            nonlocal ans

            if node is None:
                return

            paths.append(node)

            if node.left is None and node.right is None:
                ans.append("->".join([str(node.val) for node in paths]))

            if node.left:
                dfs(node.left, paths)

            if node.right:
                dfs(node.right, paths)

            paths.pop()

        paths = []
        dfs(root, paths)

        return ans