Open In App

Print all K-sum levels in a Binary Tree

Last Updated : 31 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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“.

Examples: 

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

Approach: 

  • Perform level order traversal of the Binary tree and store find the sum of each level.
  • If the sum is equal to K, print 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: 

C++




// C++ program to print all
// K-sum levels in a Binary Tree
#include <bits/stdc++.h>
using namespace std;
 
// Vector to store the
// elements of a level
vector<int> level;
 
// Binary Tree Node
struct node {
    struct node* left;
    int data;
    struct node* right;
};
 
// Function to display elements
void display(bool flag)
{
 
    // Check if boolean variable is true
    // then print the level
    if (flag) {
 
        for (auto x : level)
            cout << x << " ";
    }
 
    else
 
        cout << "Not Possible\n";
}
 
// Function to find sum of
// elements by level order traversal
void SumlevelOrder(node* root, int k)
{
 
    if (root == NULL)
        return;
 
    // Queue data structure for
    // level order traversal
    queue<node*> q;
 
    // Enqueue Root in Queue
    q.push(root);
 
    bool flag = false;
 
    while (q.empty() == false) {
 
        // number of nodes at current level
        int nodeCount = q.size();
 
        int Present_level_sum = 0;
 
        // Dequeue all nodes of current level and
        // Enqueue all nodes of next level
        while (nodeCount > 0) {
 
            node* node = q.front();
 
            // To add node data
            Present_level_sum += node->data;
 
            level.push_back(node->data);
 
            q.pop();
 
            if (node->left != NULL)
                q.push(node->left);
 
            if (node->right != NULL)
                q.push(node->right);
 
            nodeCount--;
        }
 
        if (Present_level_sum == k) {
 
            flag = true;
            break;
        }
 
        level.clear();
    }
 
    display(flag);
}
 
// Function to create a new tree node
node* newNode(int data)
{
    node* temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
 
// Driver code
int main()
{
    // Create binary tree
    node* root = newNode(1);
 
    root->left = newNode(2);
    root->right = newNode(3);
 
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->right = newNode(6);
 
    int K = 15;
 
    SumlevelOrder(root, K);
 
    return 0;
}


Java




// Java program to print all
// K-sum levels in a Binary Tree
import java.util.*;
 
class GFG{
  
// Vector to store the
// elements of a level
static Vector<Integer> level = new Vector<Integer>();
  
// Binary Tree Node
static class node {
    node left;
    int data;
    node right;
};
  
// Function to display elements
static void display(boolean flag)
{
  
    // Check if boolean variable is true
    // then print the level
    if (flag) {
  
        for (Integer x : level)
            System.out.print(x+ " ");
    }
  
    else
  
        System.out.print("Not Possible\n");
}
  
// Function to find sum of
// elements by level order traversal
static void SumlevelOrder(node root, int k)
{
  
    if (root == null)
        return;
  
    // Queue data structure for
    // level order traversal
    Queue<node> q = new LinkedList<>();
  
    // Enqueue Root in Queue
    q.add(root);
  
    boolean flag = false;
  
    while (q.isEmpty() == false) {
  
        // number of nodes at current level
        int nodeCount = q.size();
  
        int Present_level_sum = 0;
  
        // Dequeue all nodes of current level and
        // Enqueue all nodes of next level
        while (nodeCount > 0) {
  
            node node = q.peek();
  
            // To add node data
            Present_level_sum += node.data;
  
            level.add(node.data);
  
            q.remove();
  
            if (node.left != null)
                q.add(node.left);
  
            if (node.right != null)
                q.add(node.right);
  
            nodeCount--;
        }
  
        if (Present_level_sum == k) {
  
            flag = true;
            break;
        }
  
        level.clear();
    }
  
    display(flag);
}
  
// Function to create a new tree node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
  
// Driver code
public static void main(String[] args)
{
    // Create binary tree
    node root = newNode(1);
  
    root.left = newNode(2);
    root.right = newNode(3);
  
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.right = newNode(6);
  
    int K = 15;
  
    SumlevelOrder(root, K);
  
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to print all
# K-sum levels in a Binary Tree
from collections import deque as queue
 
# A BST node
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.left = None
        self.right = None
 
# Vector to store the
# elements of a level
level = []
 
# Function to display elements
def display(flag):
     
    # Check if boolean variable is
    # true then print level
    if (flag):
        for x in level:
            print(x, end = " ")
    else:
        print("Not Possible\n")
 
# Function to find sum of elements
# by level order traversal
def SumlevelOrder(root, k):
     
    if (root == None):
        return
 
    # Queue data structure for
    # level order traversal
    q = queue()
 
    # Enqueue Root in Queue
    q.append(root)
 
    flag = False
 
    while (len(q) > 0):
 
        # Number of nodes at current level
        nodeCount = len(q)
 
        Present_level_sum = 0
 
        # Dequeue all nodes of current level
        # and Enqueue all nodes of next level
        while (nodeCount > 0):
            node = q.popleft()
 
            # To add node data
            Present_level_sum += node.data
 
            level.append(node.data)
 
            # q.pop()
 
            if (node.left != None):
                q.append(node.left)
 
            if (node.right != None):
                q.append(node.right)
 
            nodeCount -= 1
 
        if (Present_level_sum == k):
            flag = True
            break
 
        level.clear()
 
    display(flag)
 
# Driver code
if __name__ == '__main__':
     
    # Create binary tree
    root = Node(1)
 
    root.left = Node(2)
    root.right = Node(3)
 
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(6)
 
    K = 15
 
    SumlevelOrder(root, K)
 
# This code is contributed by mohit kumar 29


C#




// C# program to print all
// K-sum levels in a Binary Tree
using System;
using System.Collections.Generic;
 
class GFG{
   
// List to store the
// elements of a level
static List<int> level = new List<int>();
   
// Binary Tree Node
class node {
    public node left;
    public int data;
    public node right;
};
   
// Function to display elements
static void display(bool flag)
{
   
    // Check if bool variable is true
    // then print the level
    if (flag) {
   
        foreach (int x in level)
            Console.Write(x+ " ");
    }
   
    else
   
        Console.Write("Not Possible\n");
}
   
// Function to find sum of
// elements by level order traversal
static void SumlevelOrder(node root, int k)
{
   
    if (root == null)
        return;
   
    // Queue data structure for
    // level order traversal
    Queue<node> q = new Queue<node>();
   
    // Enqueue Root in Queue
    q.Enqueue(root);
   
    bool flag = false;
   
    while (q.Count!=0) {
   
        // number of nodes at current level
        int nodeCount = q.Count;
   
        int Present_level_sum = 0;
   
        // Dequeue all nodes of current level and
        // Enqueue all nodes of next level
        while (nodeCount > 0) {
   
            node node = q.Peek();
   
            // To add node data
            Present_level_sum += node.data;
   
            level.Add(node.data);
   
            q.Dequeue();
   
            if (node.left != null)
                q.Enqueue(node.left);
   
            if (node.right != null)
                q.Enqueue(node.right);
   
            nodeCount--;
        }
   
        if (Present_level_sum == k) {
   
            flag = true;
            break;
        }
   
        level.Clear();
    }
   
    display(flag);
}
   
// Function to create a new tree node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
   
// Driver code
public static void Main(String[] args)
{
    // Create binary tree
    node root = newNode(1);
   
    root.left = newNode(2);
    root.right = newNode(3);
   
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.right = newNode(6);
   
    int K = 15;
   
    SumlevelOrder(root, K);
   
}
}
  
// This code is contributed by sapnasingh4991


Javascript




<script>
 
// Javascript program to print all
// K-sum levels in a Binary Tree
 
// Vector to store the
// elements of a level
let level = [];
 
// Binary Tree Node
class Node
{
     
    // Utility function to create a new node
    constructor(key)
    {
        this.data = key;
        this.left = this.right = null;
    }
}
 
// Function to display elements
function display(flag)
{
     
    // Check if boolean variable is true
    // then print the level
    if (flag)
    {
        for(let x = 0; x < level.length; x++)
            document.write(level[x] + " ");
    }
    else
        document.write("Not Possible<br>");
}
 
// Function to find sum of
// elements by level order traversal
function SumlevelOrder(root, k)
{
    if (root == null)
        return;
   
    // Queue data structure for
    // level order traversal
    let q = [];
   
    // Enqueue Root in Queue
    q.push(root);
   
    let flag = false;
   
    while (q.length != 0)
    {
         
        // Number of nodes at current level
        let nodeCount = q.length;
   
        let Present_level_sum = 0;
   
        // Dequeue all nodes of current level and
        // Enqueue all nodes of next level
        while (nodeCount > 0)
        {
            let node = q[0];
   
            // To add node data
            Present_level_sum += node.data;
   
            level.push(node.data);
            q.shift();
   
            if (node.left != null)
                q.push(node.left);
   
            if (node.right != null)
                q.push(node.right);
   
            nodeCount--;
        }
           
        if (Present_level_sum == k)
        {
            flag = true;
            break;
        }
        level = [];
    }
    display(flag);
}
 
// Driver code
let root = new Node(1);
 
root.left = new Node(2);
root.right = new Node(3);
 
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);
 
let K = 15;
 
SumlevelOrder(root, K);
 
// This code is contributed by unknown2108
 
</script>


Output: 

4 5 6

 

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.



Similar Reads

Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
Given a Complete Binary Tree as an array, the task is to print all of its levels in sorted order.Examples: Input: arr[] = {7, 6, 5, 4, 3, 2, 1} The given tree looks like 7 / \ 6 5 / \ / \ 4 3 2 1 Output: 7 5 6 1 2 3 4 Input: arr[] = {5, 6, 4, 9, 2, 1} The given tree looks like 5 / \ 6 4 / \ / 9 2 1 Output: 5 4 6 1 2 9 Approach: A similar problem is
6 min read
Print all nodes between two given levels in Binary Tree
Given a binary tree, print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. In the above tree, if the starting level is 2 and the ending level is 3 then the solution should print: 2 3 4 5 6 7 Note: Level number starts with 1. That is, the root node i
15 min read
Print all Palindromic Levels Of a Binary Tree
Given a Binary Tree, the task is to print all palindromic levels of this tree. Palindrome Level Any level of a Binary tree is said to be a palindromic level if on traversing it from left to right, the result is same as traversing that level from right to left. Examples: Input: 1 / \ 12 13 / / \ 11 6 11 \ / 2 2 Output: 1 11 6 11 2 2 Explanation: Fir
11 min read
Print all Prime Levels of a Binary Tree
Given a Binary Tree, the task is to print all prime levels of this tree. Any level of a Binary tree is said to be a prime level, if all nodes of this level are prime. Examples: Input: 1 / \ 15 13 / / \ 11 7 29 \ / 2 3 Output: 11 7 29 2 3 Explanation: Third and Fourth levels are prime levels. Input: 7 / \ 23 41 / \ \ 31 16 3 / \ \ / 2 5 17 11 / 23 O
14 min read
Print all Co-Prime Levels of a Binary Tree
Given a Binary Tree, the task is to print all Co-prime levels of this tree. Any level of a Binary tree is said to be a Co-prime level, if all nodes of this level are co-prime to each other. Examples: Input: 1 / \ 15 5 / / \ 11 4 15 \ / 2 3 Output: 1 11 4 15 2 3 Explanation: First, Third and Fourth levels are co-prime levels. Input: 7 / \ 21 14 / \
16 min read
Print all Exponential Levels of a Binary Tree
Given a Binary Tree, the task is to print all the Exponential Levels in the given Binary Tree. An Exponential Level is a level whose all nodes of that levels equals to xy, &amp; where x is a minimum possible positive constant &amp; y is a variable positive integer. Examples: Input: 20 / \ 9 81 / \ / \ 3 10 70 243 / \ 81 909 Output: 20 9 81 Explanat
17 min read
Print alternate nodes from all levels of a Binary Tree
Given a binary tree, the task is to traverse each level of the given binary tree from left to right and print every alternate encountered at a level. Examples: Input: Output: 1 2 3 9 5 7 Input: Output: 71 88 4 6 8 10 13 Approach: The problem can be solved by performing Level Order Traversal traversal on the given binary tree. Follow the steps below
6 min read
Print Levels of all nodes in a Binary Tree
Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key, then your function should return 0. Input: 3 / \
7 min read
Sum of all the levels in a Binary Search Tree
Given a Binary Search Tree, the task is to find the horizontal sum of the nodes that are at the same level.Examples: Input: Output: 6 12 24Input: Output: 6 12 12 Approach DFS: Find the height of the given binary tree then the number of levels in the tree will be levels = height + 1. Now create an array sum[] of size levels where sum[i] will store t
18 min read
Maximum sum of leaf nodes among all levels of the given binary tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of leaf nodes among all level of the given binary tree.Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 2 Sum of all leaves at 0th level is 0. Sum of all leaves at 1st level is -5. Sum of all leaves at 2nd level is 2. Hence maximum sum is 2. Input: 1 / \ 2 3 / \
9 min read
Article Tags :
Practice Tags :