VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-leaf-nodes-at-each-horizontal-level-in-a-binary-tree/

⇱ Sum of leaf nodes at each horizontal level in a binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of leaf nodes at each horizontal level in a binary tree

Last Updated : 23 Jul, 2025

Given a Binary Tree, the task is to find the sum of leaf nodes at every level of the given tree.

Examples:

Input:

👁 Image

Output:
0
0
6
30
12
Explanation:
Level 1: No leaf node, so sum = 0
Level 2: No leaf node, so sum = 0
Level 3: One leaf node: 6, so sum = 6 
Level 4: Three leaf nodes: 9, 10, 11, so sum = 30
Level 5: One leaf node: 12, so sum = 12

Input:

👁 Image

Output:
0
0
6
28

Approach: The given problem can be solved by using the Level Order Traversal. Follow the steps below to solve the given problem:

  • Create a queue qu, to store the node alongside its level. Also, create a map to store the sum of each level.
  • Perform the level order traversal from the root node and store each node with its level in the queue, and also check the current node for the leaf node. If it's a leaf node then add its value in the map corresponding to its level.
  • After completing the above steps, print the values in the map as the sum of each level of the given tree.

Below is the implementation of the above approach:


Output
0
0
6
30
12

Time Complexity: O(N)
Auxiliary Space: O(N)

Another Approach(Recursive):
Follow the below steps to solve the problem:
1). In this method we will traverse the each node of binary tree recursively and keep track of level with each node.
2). If the current node is leaf node then we will store the node value in vector otherwise if the node is not leaf node then we will add the sum in 0 so it will not effects out answer.
3). Finally print the array of answers.

Below is the implementation of the above approach:


Output
0
0
6
30
12

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of binary tree due to recursion.

Comment