Given a weighted tree containing N nodes, and two nodes u and v, the task is to find the count of nodes having prime weight on the simple path between u and v (both inclusive).
Approach: To solve th problem mentioned above, the idea is to use the basic concept when we find the LCA of two nodes.
- Precompute all the prime numbers till MAX using Seive method to check if a number is prime or not in O(1)
- Given two nodes u and v, we will make both nodes at the same level, by moving the greater level node move upwards. As we move up we will also check if the weight is prime or not.
- If v == u then we will simply check the weight of current node and return the count.
- If v is not equal to u then we will move both u and v upward by 1 till they are not same.
- Now we will finally check the weight of the first ancestor of u or v and return the count.
Below is the implementation of the above approach:
Time Complexity: O(N)
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.
- Count the nodes in the given tree whose weight is prime
- Count of Nodes which has Prime Digit sum weight in a Tree
- Count the nodes in the given tree whose weight is even
- Count the nodes in the given tree whose weight is even parity
- Count the nodes of the given tree whose weight has X as a factor
- Count the nodes in the given tree whose weight is a power of two
- Count the nodes in the given tree whose sum of digits of weight is odd
- Count the nodes in the given tree whose weight is a powerful number
- Count the nodes in the given Tree whose weight is a Perfect Number
- Count nodes in the given tree whose weight is a fibonacci number
- Count of nodes in a Binary Tree whose immediate children are co-prime
- Count of nodes in a Binary Tree whose child is its prime factors
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count the nodes whose weight is a perfect square
- Query to find the maximum and minimum weight between two nodes in the given tree using LCA.
- Count of Nodes whose both immediate children are its prime factors
- Print the nodes of the Binary Tree whose height is a Prime number
- Print the nodes with a prime degree in given Prufer sequence of a Tree
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- Count of Prime Nodes of a Singly Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.