Given an infinite tree and three numbers N, M, and X which has exactly N child from every node. Every edge has a weight of 1, 2, 3, 4..N. The task is to find the count of paths whose weight is exactly X and has a minimum of one edge of weight M in it.
The diagram above shows a tree shown till level-3 and N = 3.
Input: N = 3, M = 2, X = 3 Output: 2 The path 1-2 and 2-1 in the image above Input: N = 2, M = 1, X = 4 Output: 4
Approach: The problem can be solved using Dynamic Programming and memoization. We will use a top-down approach to solve this problem. Recur starting from the root with sum initially as X, and recursively traverse all paths possible( which is from 1 to N). If the node is equal to M, then the second parameter becomes true, else it stays the same which has been passed in the previous call. Store the value in a DP table to avoid visiting same states twice.
Below is the implementation of the above approach.
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.
- Count number of times each Edge appears in all possible paths of a given Tree
- Count the nodes of the given tree whose weight has X as a factor
- Queries to find the count of shortest paths in a Tree that contains a given edge
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Product of minimum edge weight between all pairs of a Tree
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Maximum sum in an array such that every element has exactly one adjacent element to it
- Number of Paths of Weight W in a K-ary tree
- Number of ways of cutting a Matrix such that atleast one cell is filled in each part
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Choose maximum weight with given weight and value ratio
- Count of Nodes which has Prime Digit sum weight in a Tree
- Number of paths with exactly k coins
- Number of unique paths in tree such that every path has a value greater than K
- Count unique paths is a matrix whose product of elements contains odd number of divisors
- Count nodes in the given tree whose weight is a fibonacci number
- 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 of root to leaf paths whose permutation is palindrome in a Binary Tree
- Count the nodes whose weight is a perfect square
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.