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, sum of these nodes = 22
In the previous article we discussed a recursive solution which first finds the maximum level and then finds the sum of all nodes present at that level.
In this article we will see a recursive solution without finding the height or depth. The idea is that while traversing the nodes compare the level of the node with max_level (Maximum level till the current node). If the current level exceeds the maximum level, update the max_level as current level. If the max level and current level are same, add the root data to current sum otherwise if level is less than max_level, do nothing.
Below is the implementation of the above approach:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sum of nodes at maximum depth of a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Find maximum among all right nodes in Binary Tree
- Maximum sum of nodes in Binary tree such that no two are adjacent
- Maximum sum of leaf nodes among all levels of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Find maximum count of duplicate nodes in a Binary Search Tree
- Maximum length cycle that can be formed by joining two nodes of a binary tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Replace node with depth in a binary tree
- Find Minimum Depth of a Binary Tree
- Depth of the deepest odd level node in Binary Tree
- Calculate depth of a full Binary tree from Preorder
- Minimum valued node having maximum depth in an N-ary Tree
- Write a Program to Find the Maximum Depth or Height of a Tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Sum of all nodes in a binary 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 firstname.lastname@example.org. 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.