Problem 741
Root to Node Path in a Binary Tree
Medium · 20 pts · Tree, Depth-First Search, Backtracking
Problem
The binary tree has distinct values, and the second input part names a target value that is in the tree. Print the values on the path from the root down to the target node, inclusive. Search with depth-first recursion that pushes the current node onto a path list, returns true as soon as the target is found in either subtree, and pops the node again when neither subtree contains it.
Input
The first line contains TARGET. The next two lines describe the tree: N, the number of tokens, then N level-order tokens with 'null' for missing children. All values are distinct.
Output
Print the values from the root to the target node, separated by spaces.
Constraints
1 <= number of nodes <= 10000; values are distinct; TARGET is in the tree
Example input
7 11 1 2 3 4 5 null null null null 6 7
Example output
1 2 5 7
Explanation
In the tree 1 2 3 4 5 null null null null 6 7 with target 7, the path from the root is 1 → 2 → 5 → 7, so the answer is 1 2 5 7.