Step-By-Step Directions From a Binary Tree Node to Another (LeetCode 2096): Solution and Explanation

Medium
String
Tree
Depth First Search
Binary Tree

Return the shortest L/R/U route between two nodes of a binary tree. Build the root-to-node direction strings for both, cut their common prefix, and stitch the rest together.

Intuition

In a tree there is exactly one simple path between two nodes. It goes up from the start to their lowest common ancestor and then down to the destination, so the answer is some number of U steps followed by L and R steps.

Directions from the root are easy to record with a DFS. The root-to-start string and the root-to-destination string agree on every step until the two paths separate, and that separation point is the lowest common ancestor.

Once the shared prefix is removed, what remains of the start path counts how far the start is below the ancestor: each of those letters becomes a U. What remains of the destination path is exactly the downward route, letter for letter.

Approach: Root paths plus common prefix

  1. DFS from the root to find startValue, appending L or R at each step and removing it when backtracking.
  2. Do the same for destValue.
  3. Advance i while both strings have the same letter at position i.
  4. Return 'U' * (len(to_start) - i) followed by to_dest[i:].

Step-by-step example

root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
  1. The DFS reaches 3 by going left to 1 and left again, so to_start = "LL".
  2. It reaches 6 by going right to 2 and then left, so to_dest = "RL".
  3. The first letters already differ (L vs R), so the common prefix is empty and the lowest common ancestor is the root 5.
  4. Both letters of to_start become U, giving "UU". Append to_dest from position 0, "RL".
  5. The answer is "UURL".

Code: Python, Java, C++

1class Solution:
2    def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
3        def find(node, target, path):
4            if not node:
5                return False
6            if node.val == target:
7                return True
8            path.append('L')
9            if find(node.left, target, path):
10                return True
11            path[-1] = 'R'
12            if find(node.right, target, path):
13                return True
14            path.pop()
15            return False
16
17        to_start, to_dest = [], []
18        find(root, startValue, to_start)
19        find(root, destValue, to_dest)
20        i = 0
21        while i < len(to_start) and i < len(to_dest) and to_start[i] == to_dest[i]:
22            i += 1
23        return 'U' * (len(to_start) - i) + ''.join(to_dest[i:])
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each DFS visits every node at most once, and comparing the strings is O(h).

Space

O(h)

The two direction strings and the recursion stack are as long as the tree height h.

Other approaches

Find the LCA first (time O(n), space O(h))

Compute the lowest common ancestor with the classic recursive LCA, then build the path from the LCA to each node. Same complexity, a little more code.

Parent map plus BFS (time O(n), space O(n))

Record every node's parent, then BFS from the start over left, right and parent edges until the destination is reached, keeping the move letters. It works for general graphs but uses O(n) memory.

Common mistakes

  • Building the path with string concatenation at every recursive call, which copies the string repeatedly and becomes O(n * h).
  • Forgetting to remove the last letter when a branch does not contain the target.
  • Turning the remaining destination letters into U instead of the remaining start letters. U steps belong to the start side.
  • Deep recursion on a skewed tree with 10^5 nodes can overflow the stack in some languages; an iterative DFS avoids that.

Frequently asked questions

Why does the common prefix lead to the lowest common ancestor?

Both strings describe walks from the root. They make identical moves while both targets are in the same subtree, and the first different letter is where the targets fall into different subtrees, which is the lowest common ancestor.

What if one node is an ancestor of the other?

Then one string is a prefix of the other. If the destination is the ancestor, the answer is only U steps; if the start is the ancestor, it is only L and R steps.

Is the answer unique?

Yes. A tree has exactly one simple path between two nodes, so there is only one shortest direction string.