Skip to content

Latest commit

 

History

History
32 lines (28 loc) · 864 Bytes

257.md

File metadata and controls

32 lines (28 loc) · 864 Bytes

257. Binary Tree Paths

Solution 1 (time O(n), space O(1))

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

        def dfs(root, cur_path):
            cur_path += str(root.val)
            if not root.left and not root.right:
                self.ans.append(cur_path)
                return
            if root.left:
                dfs(root.left, cur_path + "->")
            if root.right:
                dfs(root.right, cur_path + "->")
        
        dfs(root, "")
        return self.ans