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) or R(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 , or

    • in other words path from

  • Thus, putting all these together. Lets write a step-by-step algorithm to get directions :

    1. First of all find the LCA node of start and destination.

    2. Then we need to get path from lca_to_start and from lca_to_destination.

    3. To get path from root -> node as a string, we will use traverse() 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.

    4. Now that we have both paths, we will convert all chars in lca_to_start to U, since we will move upward.

    5. 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

circle-info

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)

circle-info

O(h) + O(N) = O(N)

Final is O(N) for skewed tree

Solution

Last updated