![]() |
VOOZH | about |
Given a Binary Tree, the task is to find the sum of leaf nodes at every level of the given tree.
Examples:
Input:
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 = 12Input:
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:
Below is the implementation of the above approach:
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:
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.