Given a Binary Tree and an integer K where the tree has positive and negative nodes, the task is to print the elements of the level whose sum equals K. If no such result exists, then print “Not Possible“.
Input: -10 / \ 2 -3 / \ \ 4 15 -6 / \ / 7 -8 9 K = 13 Output: 4 15 -6 Explanation: Level 1 (-10): Sum = -10 Level 2 (2, 3): Sum = 5 Level 3 (4, 15, -6): Sum = 13 Level 4 (7, -8, 9): Sum = 8 Only level 3 (4, 15, -6) has sum = K Input: 1 / \ 12 13 / / \ 11 6 -11 \ / 2 2 K = 30 Output: Not Possible Explanation: There is no such level whose sum = K
- Perform level order traversal of the Binary tree and store find the sum of each level.
- If the sum is equal to K, prin the level. Else move to the next level.
- The process is repeated till all the levels has been traversed and checked.
- If there is no such level with sum K, print “Not Possible”.
Below is the implementation of the above approach:
4 5 6
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print all Palindromic Levels Of a Binary Tree
- Print all Exponential Levels of a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Print Levels of all nodes in a Binary Tree
- Print all Co-Prime Levels of a Binary Tree
- Print all Prime Levels of a Binary Tree
- Print Binary Tree levels in sorted order
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Print odd positioned nodes of even levels in level order of the given binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Print the nodes at odd levels of a tree
- Averages of Levels in Binary Tree
- Left-Right traversal of all the levels of Binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Reverse alternate levels of a perfect binary tree
- Maximum sum of leaf nodes among all levels of the given 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.