Path Sum II
Practice this coding question on Coding Gurukul.
Problem statement
A decision tree attaches a signed score to each checkpoint. An analyst needs every complete route whose accumulated score matches a requested target. Your task Find all root-to-leaf paths whose node values sum to target. Important details Nodes have IDs 1 through n; node 1 is the root when the tree is nonempty. Child ID 0 means no child. A leaf has no children. A matching prefix that ends at an internal node is not a result. Negative scores are allowed, so do not stop merely because a partial sum exceeds the target. Print value sequences in numeric lexicographic order, with a shorter prefix first. Keep duplicate sequences when different physical paths have identical values. Worked example With root value 5, a left leaf valued 2 and a right leaf valued 4, target 7 selects only the path 5 2. The root alone is not a complete route, even if the target were 5.
Input format
First line: n and target. Next line: n node values in ID order (omit for n = 0). Next n lines: left and right child IDs for nodes 1 through n. The links form a valid rooted binary tree.
Output format
Print the number of matching paths, followed by one space-separated value sequence per line in numeric lexicographic order. Print only 0 when none match.
Constraints
0 <= n <= 1000; -1000 <= node values, target <= 1000.
Sample input
3 7 5 2 4 2 3 0 0 0 0
Sample output
1 5 2
Sign in to run or submit a solution in C++, Java or Python.