257. Binary Tree Paths

257. Binary Tree Paths

[Easy] “Given a binary tree, return all root-to-leaf paths."

Link to Leetcode

Note: old solution, should review (TODO:)

Python3:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        res = []
        
        if not root:
            return []
        
        def paths(node, accum=""):
            accum += str(node.val)
            if node.left:
                paths(node.left, accum + "->")
            if node.right:
                paths(node.right, accum + "->")

            # terminate
            if not node.left and not node.right:
                res.append(accum)
        
        paths(root)
        
        return res