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
Approach: Calculate the max depth of the given tree. Now, start traversing the tree similarly as traversed during maximum depth calculation. But, this time with one more argument (i.e. maxdepth), and traverse recursively with decreasing depth by 1 for each left or right call. Wherever max == 1, means the node at max depth is reached. So add its data value to sum. Finally, return sum.
Below is the implementation for above approach:
Time Complexity: O(N), where N is the number of nodes in the tree.
- Sum of nodes at maximum depth of a Binary Tree | Set 2
- 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
- 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
- Calculate depth of a full Binary tree from Preorder
- Depth of the deepest odd level node in Binary Tree
- Write a Program to Find the Maximum Depth or Height of a Tree
- Sum of all nodes in a binary tree
- Sink Odd nodes in Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Product of all nodes in a Binary Tree
- Sum of all leaf nodes of 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.
Improved By : shrikanth13