257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

Solution: DFS

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        paths = []

        def dfs(node, path):
            if not node:
                return True
            path.append(str(node.val))
            left = dfs(node.left, path)
            right = dfs(node.right, path)
            if left and right:
                paths.append('->'.join(path))
            path.pop()
            return False

        dfs(root, [])
        return paths

results matching ""

    No results matching ""