Sum of all the levels in a Binary Search Tree - GeeksforGeeks

02 Nov, 2021
Given a Binary Search Tree, the task is to find the horizontal sum of the nodes that are in the same level.Examples:  
Input:  
Output: 6 12 24Input:  
Output: 6 12 12  
 
Approach: 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 the sum of all the nodes at the ith level. In order to update this array, write a recursive function that add the current node’s data at sum[level] where level is the level of the current node and then recursively call the same method for the child nodes with level as level + 1.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>#include <queue>using namespace std; // A Binary Tree Nodestruct Node {    int data;    struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){    Node* temp = new Node;    temp->data = data;    temp->left = temp->right = NULL;    return temp;} // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){    for (int i = 0; i < n; i++)        cout << arr[i] << endl;} // Function to return the height// of the binary treeint getHeight(Node* root){    if (root->left == NULL && root->right == NULL)        return 0;     int left = 0;    if (root->left != NULL)        left = getHeight(root->left);     int right = 0;    if (root->right != NULL)        right = getHeight(root->right);     return (max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelvoid calculateLevelSum(Node* node, int level, int sum[]){    if (node == NULL)        return;     // Add current node data to the sum    // of the current node's level    sum[level] += node->data;     // Recursive call for left and right sub-tree    calculateLevelSum(node->left, level + 1, sum);    calculateLevelSum(node->right, level + 1, sum);} // Driver codeint main(){    // Create the binary tree    Node* root = newNode(6);    root->left = newNode(4);    root->right = newNode(8);    root->left->left = newNode(3);    root->left->right = newNode(5);    root->right->left = newNode(7);    root->right->right = newNode(9);     // Count of levels in the    // given binary tree    int levels = getHeight(root) + 1;     // To store the sum at every level    int sum[levels] = { 0 };    calculateLevelSum(root, 0, sum);     // Print the required sums    printArr(sum, levels);     return 0;}
// Java implementation of the approachclass Sol{     // A Binary Tree Nodestatic class Node{    int data;    Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){    for (int i = 0; i < n; i++)        System.out.print(arr[i]+ " " );} // Function to return the height// of the binary treestatic int getHeight(Node root){    if (root.left == null && root.right == null)        return 0;     int left = 0;    if (root.left != null)        left = getHeight(root.left);     int right = 0;    if (root.right != null)        right = getHeight(root.right);     return (Math.max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelstatic void calculateLevelSum(Node node, int level, int sum[]){    if (node == null)        return;     // Add current node data to the sum    // of the current node's level    sum[level] += node.data;     // Recursive call for left and right sub-tree    calculateLevelSum(node.left, level + 1, sum);    calculateLevelSum(node.right, level + 1, sum);} // Driver codepublic static void main(String args[]){    // Create the binary tree    Node root = newNode(6);    root.left = newNode(4);    root.right = newNode(8);    root.left.left = newNode(3);    root.left.right = newNode(5);    root.right.left = newNode(7);    root.right.right = newNode(9);     // Count of levels in the    // given binary tree    int levels = getHeight(root) + 1;     // To store the sum at every level    int sum[]=new int[levels];    calculateLevelSum(root, 0, sum);     // Print the required sums    printArr(sum, levels);}} // This code is contributed by andrew1234
# Python3 implementation of above algorithm # Utility class to create a nodeclass Node:    def __init__(self, key):        self.data = key        self.left = self.right = None         # Utility function to create a tree nodedef newNode( data):     temp = Node(0)    temp.data = data    temp.left = temp.right = None    return temp # Utility function to print# the contents of an arraydef printArr(arr, n):     i = 0    while ( i < n):        print( arr[i])        i = i + 1 # Function to return the height# of the binary treedef getHeight(root):     if (root.left == None and root.right == None):        return 0     left = 0    if (root.left != None):        left = getHeight(root.left)     right = 0    if (root.right != None):        right = getHeight(root.right)     return (max(left, right) + 1) sum = [] # Recursive function to update sum[] array# such that sum[i] stores the sum# of all the elements at ith leveldef calculateLevelSum(node, level):         global sum    if (node == None):        return     # Add current node data to the sum    # of the current node's level    sum[level] += node.data     # Recursive call for left and right sub-tree    calculateLevelSum(node.left, level + 1)    calculateLevelSum(node.right, level + 1)  # Driver code # Create the binary treeroot = newNode(6)root.left = newNode(4)root.right = newNode(8)root.left.left = newNode(3)root.left.right = newNode(5)root.right.left = newNode(7)root.right.right = newNode(9) # Count of levels in the# given binary treelevels = getHeight(root) + 1 # To store the sum at every levelsum = [0] * levelscalculateLevelSum(root, 0) # Print the required sumsprintArr(sum, levels) # This code is contributed by Arnab Kundu
// C# implementation of the approachusing System;class GFG{     // A Binary Tree Nodepublic class Node{    public int data;    public Node left, right;}; // Utility function to create a new tree nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){    for (int i = 0; i < n; i++)        Console.WriteLine(arr[i]);} // Function to return the height// of the binary treestatic int getHeight(Node root){    if (root.left == null &&        root.right == null)        return 0;     int left = 0;    if (root.left != null)        left = getHeight(root.left);     int right = 0;    if (root.right != null)        right = getHeight(root.right);     return (Math.Max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelstatic void calculateLevelSum(Node node, int level,                                         int []sum){    if (node == null)        return;     // Add current node data to the sum    // of the current node's level    sum[level] += node.data;     // Recursive call for left and right sub-tree    calculateLevelSum(node.left, level + 1, sum);    calculateLevelSum(node.right, level + 1, sum);} // Driver codepublic static void Main(String []args){    // Create the binary tree    Node root = newNode(6);    root.left = newNode(4);    root.right = newNode(8);    root.left.left = newNode(3);    root.left.right = newNode(5);    root.right.left = newNode(7);    root.right.right = newNode(9);     // Count of levels in the    // given binary tree    int levels = getHeight(root) + 1;     // To store the sum at every level    int []sum = new int[levels];    calculateLevelSum(root, 0, sum);     // Print the required sums    printArr(sum, levels);}} // This code is contributed by 29AjayKumar
<script>// Javascript implementation of the approach // A Binary Tree Nodeclass Node{    constructor(data)    {        this.data = data;        this.left = this.right = null;    }} // Utility function to print// the contents of an arrayfunction printArr(arr, n){    for (let i = 0; i < n; i++)        document.write(arr[i]+ " <br>" );} // Function to return the height// of the binary treefunction getHeight(root){    if (root.left == null && root.right == null)        return 0;      let left = 0;    if (root.left != null)        left = getHeight(root.left);      let right = 0;    if (root.right != null)        right = getHeight(root.right);      return (Math.max(left, right) + 1);} // Recursive function to update sum[] array// such that sum[i] stores the sum// of all the elements at ith levelfunction calculateLevelSum(node,level,sum){    if (node == null)        return;      // Add current node data to the sum    // of the current node's level    sum[level] += node.data;      // Recursive call for left and right sub-tree    calculateLevelSum(node.left, level + 1, sum);    calculateLevelSum(node.right, level + 1, sum);   } // Driver code// Create the binary treelet root = new Node(6);root.left = new Node(4);root.right = new Node(8);root.left.left = new Node(3);root.left.right = new Node(5);root.right.left = new Node(7);root.right.right = new Node(9); // Count of levels in the// given binary treelet levels = getHeight(root) + 1; // To store the sum at every levellet sum=new Array(levels);for(let i = 0; i < levels; i++)    sum[i] = 0; calculateLevelSum(root, 0, sum); // Print the required sumsprintArr(sum, levels); // This code is contributed by avanitrachhadiya2155</script>
6
12
24
 
Time Complexity : O(N)Auxiliary Space: O(N) 
andrew1234
29AjayKumar
pankajsharmagfg
avanitrachhadiya2155
gabaa406
amartyaghoshgfg
Arrays
Binary Search Tree
Data Structures
Data Structures
Arrays
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Construct BST from given preorder traversal | Set 1