VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-two-nodes-are-on-same-path-in-a-tree-set-2/

⇱ Check if two nodes are on same path in a tree | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if two nodes are on same path in a tree | Set 2

Last Updated : 15 Jul, 2025

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. 
Example: 
 

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:


Output: 
Yes

 

Time Complexity: O(N2) where N is the number of vertices in the graph.
Auxiliary Space: O(1)
 

Comment
Article Tags: