Binary Tree Paths — LeetCode 257 Python Solution

EasyTreeDepth-First SearchStringBacktrackingBinary Tree
Problem
#257
Reading time
4 min

The problem

Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children.

Example

Input
root = [1,2,3,null,5]
Output
["1->2->5","1->3"]

Python solution

Python
# 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]:
        def dfs(root: Optional[TreeNode]):
            if root is None:
                return
            t.append(str(root.val))
            if root.left is None and root.right is None:
                ans.append("->".join(t))
            else:
                dfs(root.left)
                dfs(root.right)
            t.pop()

        ans = []
        t = []
        dfs(root)
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 257. Binary Tree Paths is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 257. Binary Tree Paths?
LeetCode 257. Binary Tree Paths is rated Easy on LeetCode.
What is the time complexity of LeetCode 257. Binary Tree Paths?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 257. Binary Tree Paths?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 257. Binary Tree Paths cover?
LeetCode 257. Binary Tree Paths is tagged Tree, Depth-First Search, String, Backtracking and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview