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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- 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 | Set 2
- Print path between any two nodes in a Binary Tree
- Print the path common to the two paths from the root to the two given nodes
- Root to leaf path with maximum distinct nodes
- 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
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Print path from root to all nodes in a Complete Binary Tree
- Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
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