Given a Binary Search Tree, the task is to find the horizontal sum of the nodes that are in the same level.
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
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.
- Left-Right traversal of all the levels of Binary tree
- Print all nodes between two given levels in Binary Tree
- Print all Co-Prime Levels of a Binary Tree
- Binary Search Tree | Set 1 (Search and Insertion)
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Count the Number of Binary Search Trees present in a Binary Tree
- Difference between Binary Tree and Binary Search Tree
- Binary Tree to Binary Search Tree Conversion
- Binary Tree to Binary Search Tree Conversion using STL set
- Binary Search Tree | Set 2 (Delete)
- Floor in Binary Search Tree (BST)
- Make Binary Search Tree
- Optimal Binary Search Tree | DP-24
- Inorder Successor in Binary Search Tree
- Print all odd nodes of Binary Search Tree
- Print all even nodes of Binary Search Tree
- Construct a Binary Search Tree from given postorder
- How to handle duplicates in Binary Search Tree?
- Number of pairs with a given sum in a Binary Search 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 email@example.com. 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.