Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
Given a binary tree and an integer K, the task is to print the paths from root to leaf with the maximum element greater than or equal to K. Print -1 if there exists no such path.
Input: K = 25, 10 / \ 5 8 / \ / \ 29 2 1 98 / \ 20 50 Output: (10, 5, 29, 20), (10, 8, 98, 50) Explanation: The maximum value in the path 10 -> 5 -> 29 -> 20 is 29 which is greater than 25. The maximum value in the path 10 -> 8 -> 98 -> 50 is 98 which is greater than 25. Input: K = 5 2 / \ 1 4 / 0 Output: -1 Explanation: None of the paths from the root to a leaf has the value greater than 5.
Approach: The idea is to check if a node contains a value greater than or equal to ‘K’. If yes, then all the subtrees of that node is a valid path. The following steps can be followed to compute the answer:
- For every node, check if the current node value is greater than ‘K’ or not.
- If yes, then insert it into a vector and set a flag variable to 1. This signifies that all the paths going through this node will be printed.
- Repeat the above steps using recursion. The function is recursively called for the left and right subtrees.
- Finally, by using the concept of backtracking, print the path from the vector.
Below is the implementation of the above approach:
(10, 5, 29, 20), (10, 8, 98, 50),
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.