Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node.
1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are 4, 5, 6, 7. So, the sum of these nodes = 22
Approach: There exists a recursive approach to this problem. This can also be solved using level order traversal and map. The idea is to do a traversal using a queue and keep track of current level. A map has been used to store the sum of nodes at the current level. Once all nodes are visited and the traversal is done, the last element of the map will contain the sum at the maximum depth of the tree.
Below is the implementation of the above approach:
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Get Level of a node in a Binary Tree
- Rearrange a Linked List in Zig-Zag fashion | Set-2
- Find the maximum node at a given level in a binary tree
- Maximize the total profit of all the persons
- Reverse nodes of a linked list without affecting the special characters
- Pair with minimum absolute difference after solving each query
- Sum of cousins of a given node in a Binary Tree
- Applications of Graph Data Structure
- Insert a node at a specific position in a linked list
- Queries to insert, delete one occurrence of a number and print the least and most frequent element