Given an Acyclic Undirected Graph in the form of a Binary Tree with root at vertex 1 and values at each vertices [1, N] denoted by the array arr[], the task is to find number of root to leaf paths that contain atmost m consecutive nodes with value K.
Example:
Input:_ arr[] = {1, 0, 1, 0, 0, 1, 0}, K = 1, M = 2 _
Output:_ 3 _
Explanation:
_Path 1 : 1 -> 2 -> 4 contains maximum 1 consecutive K _
_Path 2 : 1 -> 2 -> 5 contains maximum 1 consecutive K _
_Path 3 : 1 -> 3 -> 6 contains maximum 3 consecutive K _
_Path 4 : 1 -> 3 -> 7 contains maximum 2 consecutive K _
Since the given value of M is 2, therefore there are 3 paths that contains atmost 2 consecutive K.
Input:_ arr[] = {2, 1, 3, 2, 1, 2, 1, 4, 3, 5, 2}, K = 2, M = 2 _
2
/ \
1 3
/ \ / \
2 1 2 1
/ \ / \
4 3 5 2
Output:_ 3 _
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Approach:
The problem can be solved using Depth First Search approach:
#graph #greedy #mathematical #searching #tree #dfs #tree traversals