Step-By-Step Directions From a Binary Tree Node to Another - Problem
Navigate Through a Binary Tree: Imagine you're exploring a family tree where each person has at most two children. You need to find directions from one person to another!

Given a binary tree with n nodes (each uniquely numbered from 1 to n), find the shortest path from a start node to a destination node. Your directions must be a string using only these moves:

'L' - Go to left child
'R' - Go to right child
'U' - Go up to parent

Goal: Return step-by-step directions as a string of 'L', 'R', and 'U' characters that represents the shortest path from startValue to destValue.

Think of it like GPS navigation through a tree structure - you might need to go up to a common ancestor before going down to your destination!

Input & Output

example_1.py — Basic Tree Navigation
$ Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
Output: "UURL"
💡 Note: The shortest path from 3 to 6 is: 3 → 1 (Up) → 5 (Up) → 2 (Right) → 6 (Left). This gives us directions 'UURL'.
example_2.py — Direct Parent-Child
$ Input: root = [2,1], startValue = 2, destValue = 1
Output: "L"
💡 Note: Node 1 is the direct left child of node 2, so we just need to go left once.
example_3.py — Siblings Navigation
$ Input: root = [1,null,3,2,4], startValue = 2, destValue = 4
Output: "UR"
💡 Note: From node 2, go up to parent 3, then right to node 4. Path: 2 → 3 (Up) → 4 (Right).

Visualization

Tap to expand
RootLCANodeSTARTNodeDEST① Go UP to LCA② Follow path to DESTResult: "ULRR"
Understanding the Visualization
1
Map the Routes
Find paths from the city center (root) to both your starting point and destination
2
Find Common Highway
Identify where the two routes share the same path - this is your common highway (LCA)
3
Calculate Backtrack
From your start, count how many steps back to the common highway (these become 'U' moves)
4
Navigate Forward
From the common highway, follow the remaining route to your destination
Key Takeaway
🎯 Key Insight: The shortest path in any tree structure always goes through the Lowest Common Ancestor - there are no shortcuts around this natural highway!

Time & Space Complexity

Time Complexity
⏱️
O(n²)

In worst case, we might explore all nodes multiple times to find the path

n
2n
Quadratic Growth
Space Complexity
O(n)

Recursion stack depth can go up to the height of the tree, path storage

n
2n
Linearithmic Space

Constraints

  • The number of nodes in the tree is n where 2 ≤ n ≤ 105
  • 1 ≤ Node.val ≤ n
  • All values in the tree are unique
  • startValue != destValue
  • Both startValue and destValue exist in the tree
Asked in
Amazon 45 Google 38 Microsoft 28 Meta 22
67.2K Views
Medium-High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen