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
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)
- Check if two nodes are on same path in a tree
- Queries to check if the path between two nodes in a tree is a palindrome
- XOR of path between any two nodes in a Binary Tree
- Print the path between any two nodes of a tree | DFS
- Print path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Check whether the given node is in the path between the nodes U and V
- Shortest path between two nodes in array like representation of binary tree
- Find the path from root to the given nodes of a tree for multiple queries
- Print path from root to all nodes in a Complete Binary Tree
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Check if a path exists in a tree with K vertices present or are at most at a distance D
- Check if two nodes in a Binary Tree are siblings
- Check if two nodes are cousins in a Binary Tree
- Check if two nodes are cousins in a Binary Tree | Set-2
- Check sum of Covered and Uncovered nodes of Binary Tree
- Check if all nodes of the Binary Tree can be represented as sum of two primes
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Rajput-Ji