Problem 264
Path Sum II
Medium · 20 pts · Tree, Binary Tree, Backtracking
Problem
You are given a binary tree and a target S. Print every path that starts at the root, ends at a leaf (a node with no children) and whose values add up to exactly S. Print one path per line, with its values from the root down. List the paths in the order a depth-first search reaches their leaves, exploring left subtrees before right ones. If no path works, print NONE. Use DFS with a list holding the current path: add a node when you enter it, check the sum at each leaf, and remove the node again when you return (backtracking).
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child. Third line: the target S.
Output
Print each path on its own line (values space-separated), or NONE.
Constraints
1 <= number of nodes <= 5000; -1000 <= value <= 1000; -1000000 <= S <= 1000000
Example input
13 5 4 8 11 null 13 4 7 2 null null 5 1 22
Example output
5 4 11 2 5 8 4 5
Explanation
The path 5 → 4 → 11 → 2 sums to 22, and so does 5 → 8 → 4 → 5. The first lies in the left subtree, so it is printed first. No other root-to-leaf path sums to 22.