Problem Description
Given the root of a binary tree with unique node values, and two different target node values – startValue and destValue – find the shortest path from the start node to the destination node. The answer should be returned as a string consisting of characters ‘L’, ‘R’, and ‘U’ indicating moves to a node’s left child, right child, and parent respectively.
Key Insights
- Find the path from the root to the start node and the root to the destination node using DFS.
- Identify the last common node (i.e. the lowest common ancestor, LCA) by comparing the two paths.
- The moves from the start node to the LCA are represented by ‘U’s.
- The remaining part of the destination path (from the LCA to the destination node) provides the directions (‘L’ or ‘R’).
- Concatenate the appropriate number of ‘U’s with the unique portion of the destination path to obtain the final direction string.
Space and Time Complexity
Time Complexity: O(n) – Traversing the tree using DFS and comparing paths takes linear time. Space Complexity: O(n) – In the worst-case scenario, the recursion stack and path storage will use linear space.
Solution
We solve the problem by:
- Using DFS to obtain the path from the root to the start node and from the root to the destination node. During DFS, we accumulate the direction taken (either ‘L’ or ‘R’).
- Comparing the two generated paths from the beginning to determine where they diverge. This divergence point corresponds to the lowest common ancestor (LCA).
- For the portion of the start path after the common part, each step is replaced by a ‘U’ (to move upward from the start node to the LCA).
- After reaching the LCA, append the remaining steps from the destination path to reach the destination node.
- Finally, return the concatenated instruction string.
The key data structures used are:
- Vectors/arrays (or lists) to store the path for each target node.
- Recursive DFS for tree traversal.
This approach ensures that we correctly translate the downward path information into the required “upward then downward” directions.