![]() |
VOOZH | about |
Given a root of binary tree and two integers startValue and destValue denoting the starting and ending node respectively. The task is to find the shortest path from the start node to the end node and print the path in the form of directions given below.
Examples:
Input: root = [5, 1, 2, 3, null, 6, 4], startValue = 3, destValue = 6
5
/ \
1 2
/ / \
3 6 4Output: "UURL"
Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6.Input: root = [2, 1], startValue = 2, destValue = 1
2
/
1Output: "L"
Explanation: The shortest path is: 2 → 1.
Approach: The simplest way to solve this problem is to use the LCA (Lowest Common Ancestor) of a binary tree. Follow the steps below to solve the given problem.
Below is the implementation of the above approach.
UURL
Time complexity: O(3N), Because three traversals are done.
Auxiliary Space: O(N)
Efficient Approach: This approach is implementation based but LCA is not used in this approach. Follow the steps below to solve the given problem.
Below is the implementation of the above approach.
UURL
Time complexity: O(N)
Auxiliary Space: O(N)