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 all odd nodes in the path connecting two given nodes
- Check whether a node is leaf node or not for multiple queries
- Queries to check if the path between two nodes in a tree is a palindrome
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Count of all prime weight nodes between given nodes in the given Tree
- Sum of nodes on the longest path from root to leaf node
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
- Check if two nodes are on same path in a tree | Set 2
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- Shortest path between two nodes in array like representation of binary tree
- 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
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Maximum XOR with given value in the path from root to given node in the 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