Given three vertices U, V and R of a binary tree, the task is to check whether R lies in the path between U and V. If it is not present in the path then print No otherwise print Yes.
Input: U = 4, V = 6, R = 2
Path 4 -> 2 -> 1 -> 3 -> 6 contains 2
Input: U = 4, V = 6, R = 5
Path 4 -> 2 -> 1 -> 3 -> 6 does not contain 5
Approach: The idea is to use Lowest Common Ancestor of two nodes. There are following cases for R to exist in the path between U and V:
- R is the lowest common ancestor of U and V.
- R is in the left subtree of the lowest common ancestor of U and V and is above V.
- R is in the right subtree of the lowest common ancestor of U and V and is above U.
To know more about the lowest commom ancestor, read the post here.
Below is the implementation of the above approach:
Time Complexity: O(NlogN) for pre-processing and logN for finding the lowest common ancestor.
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.
- Sum of nodes on the longest path from root to leaf node
- Check if two nodes are on same path in a tree | Set 2
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Queries to check if the path between two nodes in a tree is a palindrome
- Check if two nodes are in same subtree of the root node
- Sum of all odd nodes in the path connecting two given nodes
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Remove all nodes which don't lie in any path with sum>= k
- XOR of path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Root to leaf path with maximum distinct nodes
- Sum of Nodes and respective Neighbors on the path from root to a vertex V
- Print the path common to the two paths from the root to the two given nodes
- Minimum Cost Path in a directed graph via given set of intermediate nodes
- Find the path from root to the given nodes of a tree for multiple queries
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Print path from root to all nodes in a Complete Binary Tree
- Shortest path between two nodes in array like representation of binary tree
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 : princiraj1992