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:

  • Depth First Search can be used to traverse all the paths from the root vertex.
  • Every time if value at the present node is K, increment the count.
  • Otherwise, set count to 0.
  • If count exceeds M, then return.
  • Otherwise, traverse its neighboring nodes and repeat the above steps.
  • Finally print the value of count obtained.

#graph #greedy #mathematical #searching #tree #dfs #tree traversals

Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
1.45 GEEK