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 in the same level.
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.
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:
6 12 24
Time Complexity : O(N)
Auxiliary Space: O(N)