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.
- Number of unique paths in tree such that every path has a value greater than K
- Print all the Paths of a Binary Tree whose XOR is non-zero
- Print all k-sum paths in a binary tree
- Print Palindromic Paths of Binary tree
- Print all the paths from root, with a specified sum in Binary tree
- Root to leaf paths having equal lengths in a Binary Tree
- Given a binary tree, print all root-to-leaf paths
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Print path between any two nodes in a Binary Tree
- Print all Coprime path of a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Print path from root to a given node in a binary tree
- Maximum XOR path of a Binary Tree
- Maximum Path Sum in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Print path from root to all nodes in a Complete Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Find the maximum path sum between two leaves of a binary tree
- Maximum Consecutive Increasing Path Length in Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.