Step-By-Step Directions From a Binary Tree Node to Another

Medium

Description

Given a binary tree and two node values, return the shortest path from start to destination as a string of U (up), L (left), R (right).

Examples

Input:root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
Output:"UURL"
Explanation:

Up twice, right, left.

Input:root = [1,2,3,4,5,6,7], startValue = 4, destValue = 7
Output:UUR
Explanation:

Starting from node 4, go up to its parent node 2, then up again to the root node 1, then right to reach node 7. The path is: 4 → 2 → 1 → 3 → 7.

Input:root = [8,3,10,1,6,null,14,null,null,4,7,13,null], startValue = 7, destValue = 13
Output:UUUL
Explanation:

Starting from node 7, go up to parent node 6, then up to parent node 3, then up to root node 8, then left to reach node 13. The path traverses: 7 → 6 → 3 → 8 → 10 → 14 → 13.

Constraints

  • 2 ≤ nodes ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!