Given the root of a binary tree and an integer target_sum, return all root-to-leaf paths where the sum of the node values in the path equals target_sum. Each path should be returned as a list of the node values, from the root down to the leaf, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Function Signature
def path_sum(root: Optional[TreeNode], target_sum: int) -> List[List[int]]:
Rules
-
TreeNode
has the fields
val
,
left
and
right
. An empty tree is passed as
root = None
.
-
The examples write the tree as a level-order list, with
None
marking a missing child.
-
A path must end at a leaf. A node that has only one child is not the end of a path.
-
Return the paths sorted in ascending lexicographic order of their value lists: compare element by element, and when one list is a prefix of the other, the shorter list comes first. This is Python's default ordering for lists.
-
Two different paths that happen to have the same values both appear in the output.
-
If no path matches, or the tree is empty, return an empty list.
Constraints
-
The number of nodes in the tree is in the range
[0, 5000]
.
-
-1000 <= Node.val <= 1000
-
-1000 <= target_sum <= 1000
Examples
Input: root = [5,4,8,11,None,13,4,7,2,None,None,5,1], target_sum = 22
Output: [[5,4,11,2],[5,8,4,5]]
The leaves are 7, 2, 13, 5 and 1, and only the paths 5 -> 4 -> 11 -> 2 and 5 -> 8 -> 4 -> 5 add up to 22. [5,4,11,2] comes first because 4 < 8 in the second position.
Input: root = [1,2,3], target_sum = 5
Output: []
The only root-to-leaf paths are 1 -> 2 (sum 3) and 1 -> 3 (sum 4), so nothing matches.
Input: root = [0,2,1,-1,None,None,0], target_sum = 1
Output: [[0,1,0],[0,2,-1]]
The root 0 has a left child 2 (whose left child is -1) and a right child 1 (whose right child is 0). Both paths sum to 1, and the ordering rule puts [0,1,0] first even though its leaf is further right in the tree.