Hide sidebar

Binary Tree Paths

TreesDFS

Problem Statement

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

1253

Output: ["1→2→5", "1→3"]

Algorithm Explanation

We can solve this problem using a depth-first search (DFS) approach. We'll traverse the tree from the root, keeping track of the current path.

Algorithm Steps

  • DFS Function: Create a recursive DFS function that takes a node and the current path string as arguments.
  • Path String: At each node, append its value to the current path string.
  • Leaf Node: If the current node is a leaf, we've found a complete path. Add the path string to our result list.
  • Recursive Calls: If the node is not a leaf, make recursive calls for its left and right children, passing along the updated path string.
1253
Start
Starting DFS from the root.

Current Path

Result

Binary Tree Paths Solution

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        result = []
        
        def dfs(node, path):
            if not node:
                return
            
            path += str(node.val)
            if not node.left and not node.right:
                result.append(path)
            else:
                path += "->"
                dfs(node.left, path)
                dfs(node.right, path)

        dfs(root, "")
        return result