Step-By-Step Directions From a Binary Tree Node to Another (LeetCode 2096): Solution and Explanation
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
- DFS from the root to find
startValue, appending L or R at each step and removing it when backtracking. - Do the same for
destValue. - Advance
iwhile both strings have the same letter at positioni. - Return
'U' * (len(to_start) - i)followed byto_dest[i:].
Step-by-step example
root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
- The DFS reaches 3 by going left to 1 and left again, so to_start = "LL".
- It reaches 6 by going right to 2 and then left, so to_dest = "RL".
- The first letters already differ (L vs R), so the common prefix is empty and the lowest common ancestor is the root 5.
- Both letters of to_start become U, giving "UU". Append to_dest from position 0, "RL".
- 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:])1class Solution {
2 public String getDirections(TreeNode root, int startValue, int destValue) {
3 StringBuilder toStart = new StringBuilder();
4 StringBuilder toDest = new StringBuilder();
5 find(root, startValue, toStart);
6 find(root, destValue, toDest);
7 int i = 0;
8 while (i < toStart.length() && i < toDest.length() && toStart.charAt(i) == toDest.charAt(i)) {
9 i++;
10 }
11 StringBuilder ans = new StringBuilder();
12 for (int k = i; k < toStart.length(); k++) ans.append('U');
13 ans.append(toDest.substring(i));
14 return ans.toString();
15 }
16
17 private boolean find(TreeNode node, int target, StringBuilder path) {
18 if (node == null) return false;
19 if (node.val == target) return true;
20 path.append('L');
21 if (find(node.left, target, path)) return true;
22 path.setCharAt(path.length() - 1, 'R');
23 if (find(node.right, target, path)) return true;
24 path.deleteCharAt(path.length() - 1);
25 return false;
26 }
27}1class Solution {
2 bool find(TreeNode* node, int target, string& path) {
3 if (!node) return false;
4 if (node->val == target) return true;
5 path.push_back('L');
6 if (find(node->left, target, path)) return true;
7 path.back() = 'R';
8 if (find(node->right, target, path)) return true;
9 path.pop_back();
10 return false;
11 }
12
13public:
14 string getDirections(TreeNode* root, int startValue, int destValue) {
15 string toStart, toDest;
16 find(root, startValue, toStart);
17 find(root, destValue, toDest);
18 size_t i = 0;
19 while (i < toStart.size() && i < toDest.size() && toStart[i] == toDest[i]) {
20 i++;
21 }
22 return string(toStart.size() - i, 'U') + toDest.substr(i);
23 }
24};Time and space complexity
O(n)
Each DFS visits every node at most once, and comparing the strings is O(h).
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.