Given a binary tree, find the sum of all the leaf nodes.
Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24
The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the leaf node, add node data to sum variable.
Following is the implementation of above approach.
Time Complexity : O(n)
This article is contributed by Mandeep Singh. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- 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
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Print the longest leaf to leaf path in a Binary tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Product of all leaf nodes of binary tree
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print all leaf nodes of a binary tree from right to left
- Print all leaf nodes of a Binary Tree from left to right
- Generate Complete Binary Tree in such a way that sum of non-leaf nodes is minimum
- Check if a Binary Tree consists of a pair of leaf nodes with sum K
- Program to count leaf nodes in a binary tree
- Pairwise Swap leaf nodes in a binary tree
- Count Non-Leaf nodes in a Binary Tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Print the nodes of binary tree as they become the leaf node
- Print leaf nodes in binary tree from left to right using one stack
- Print left and right leaf nodes separately in Binary Tree