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

You are given the `root` of a binary tree with `n` nodes, each holding a unique value from `1` to `n`, plus two values `startValue` and `destValue` naming a start node `s` and a destination node `t`. Return the shortest path from `s` to `t` as a string of the letters `L` (go to the left child), `R` (go to the right child) and `U` (go to the parent).

30:00

Step-By-Step Directions From a Binary Tree Node to Another
medium
Free written solution
Topics
Companies

You are given the root of a binary tree with n nodes, each holding a unique value from 1 to n, plus two values startValue and destValue naming a start node s and a destination node t.

Return the shortest path from s to t as a string of the letters L (go to the left child), R (go to the right child) and U (go to the parent).

Example 1:
Input: {"root":[5,1,2,3,null,6,4],"startValue":3,"destValue":6}
Output: "UURL"
Constraints:
  • The number of nodes in the tree is nn, with 2≤n≤1052 \le n \le 10^5.

  • 1≤1 \le Node.val ≤n\le n, and all values are unique.

  • 1≤1 \le startValue, destValue ≤n\le n

  • startValue != destValue

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[5,1,2,3,null,6,4],"startValue":3,"destValue":6}

Go from 3 to 6. Plan: record the L/R path from the root to each node, drop the shared prefix (it leads to their lowest common ancestor), then climb with U and descend with the rest.

5123S6D4
to_start
?
to_dest
?

answer

(empty)
S start / root-to-start path
D destination / root-to-dest path
common ancestor
answer route
Variables
VariableValue
startValue3
destValue6
DepthFunction Call
Stack empty
0/14