2096. Step-By-Step Directions From a Binary Tree Node to Another
Problem
Intuition
This is a very nice problem as one require multiple concepts. Like
Lowest Common Ancestor
DFS : Tree Traversal and Backtracking (to get Path b/w nodes)
First let us make couple of observations and note it down :
How to get shortest distance/path b/w two node in Binary Tree?
We need to find closest point(from nodes), where path from root to nodes intersect
This is nothing but the LCA(Lowest Common Ancestor) of two nodes.
Now, if we move from start node to LCA node, which direction we will follow :
U(up),L(left)orR(right)?Here we can surely say since LCA always lie above the node, so we will move in upward direction.
And there can also be a case when start node itself is LCA, so no need to worry in this case.
Now coming back to our problem, we need to get shortest path from
start -> destination, orin other words path from
Thus, putting all these together. Lets write a step-by-step algorithm to get directions :
First of all find the LCA node of
startanddestination.Then we need to get path from
lca_to_startand fromlca_to_destination.To get path from
root -> nodeas a string, we will usetraverse()function.In this we simply do a simple DFS ( kind of pre-order traversal)
First explore left path, if node is found. Then return true.
Otherwise backtrack and explore right path.
Now that we have both paths, we will convert all chars in
lca_to_starttoU, since we will move upward.At last, concatenate both strings and return combined path.
Lets see this through an example :
Time Complexity
N -> Total Number of node
O(N) -> LCA
O(N) -> Traverse from LCA to start
O(N) -> Traverse from LCA to dest
O(N) + O(N) + O(N) = 3 O(N) = O(N)
Final is O(N)
Space Complexity
N -> Total Number of node
O(h) -> LCA stack space
O(N) -> In worst case, there is a skewed tree and the path from left most node to right most // node is O(N)
O(h) + O(N) = O(N)
Final is O(N) for skewed tree
Solution
Last updated