Check if two nodes are on same path in a tree | Set 2
Given two nodes of a binary tree v1 and v2, the task is to check if two nodes are on the same path in a tree.
Input: v1 = 1, v2 = 5 1 / | \ 2 3 4 / | \ 5 6 7 Output: Yes Explanation: Both nodes 1 and 5 lie in the path 1 -> 2 -> 5. Input: v1 = 2, v2 = 6 1 / | \ 2 3 4 / | \ 5 6 7 Output: NO
DFS Approach: Refer to Check if two nodes are on same path in a tree for the DFS approach.
LCA Approach: The idea is to use Lowest Common Ancestor. Find the LCA of the given vertices v1 and v2. If the LCA is equal to any of the given two vertices, print Yes. Otherwise, print No.
Below is the implementation of above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.