LeetCode 257. Binary Tree Paths

Dec 27, 2025

Intuition

Use backtracking to remember path and construct the result

  1. Initialize an empty list to store the paths.
  2. Define a helper function that takes the current node and the current path as parameters.
  3. If the current node is null, return.
  4. Append the current node's value to the current path.
  5. If the current node is a leaf node, add the current path to the list of paths.
  6. Recursively call the helper function on the left and right children of the current node.
  7. Remove the last element from the current path.

Optimal 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: Optional[TreeNode]) -> List[str]:
        res = []
        
        def dfs(node,path):
            if not node:
                return 

            path.append(str(node.val))
            if not node.left and not node.right:
                res.append("->".join(path))
            else:
                dfs(node.left, path)
                dfs(node.right,path)
            path.pop()

        dfs(root, [])
        return res

Time Complexity

Time Complexity O(N)

Space Complexity O(H)

Steve Jin