Problem
Given theroot of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Examples
Constraints
- The number of nodes in the tree is in the range
[1, 100]. -100 <= Node.val <= 100
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 257 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 257 # by problem number
lcpy gen -s binary_tree_paths # by problem name
root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
Input: root = [1]
Output: ["1"]
[1, 100].-100 <= Node.val <= 100from leetcode_py import TreeNode
class Solution:
# Time: O(n * d) where d is the average path length
# Space: O(h) for the recursion stack, excluding the output
def binary_tree_paths(self, root: TreeNode[int] | None) -> list[str]:
paths: list[str] = []
def dfs(node: TreeNode[int] | None, path: list[str]) -> None:
if node is None:
return
path.append(str(node.val))
if node.left is None and node.right is None:
paths.append("->".join(path))
else:
dfs(node.left, path)
dfs(node.right, path)
path.pop()
dfs(root, [])
return paths
| Time | Space |
|---|---|
| O(n * d) where d is the average path length | O(h) for the recursion stack, excluding the output |