CitadelOA #20
Minimum Path Sum to Target in Binary Tree
Estimated MediumJudge-ready
Topics (AI-labelled)Tree PathsTree Building
Among all root-to-leaf paths in the binary tree whose sum equals target, first choose the one with the fewest nodes, then the one whose sequence of node values is lexicographically smallest. If there is no solution, output an empty array.
Input
The first line contains m, the number of level-order token entries, and target; the second line contains m integers or null. Entries are interpreted in order as the left and right children of the non-null parents taken from a queue; trailing null tokens may be omitted, and full heap indices are not used. The original gave no numeric bounds; this site uses 0..100000 nodes, 0≤m≤200001, node values within ±10^9, and target within ±10^14; a valid level order is guaranteed, and an empty tree can be given as m=0 or a single null.
Output
The first line contains the number of nodes on the path, and the second line contains the values on the path; if there is no solution, output only 0.
Example 1
Input:
13 22
5 4 8 11 null 13 4 7 2 null null 5 1
Output:
4
5 4 11 2
Example 2
Input:
3 5
1 2 3
Output:
0
Example 3
Input:
7 0
0 2 1 -2 null null -1
Output:
3
0 1 -1
Example notes
The outputs of the three public examples are, in order: 4 / 5 4 11 2; 0; 3 / 0 1 -1. These answers were verified by independent enumeration or direct simulation.
Editorial
Loading solution…