Given a binary tree, find the product of all the leaf nodes.
Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : product = 4 * 5 * 8 * 7 = 1120
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, multiply node data to a variable prod used to store the products of leaf nodes.
Following is the implementation of above approach.
Time Complexity : O(n), where n is the total number of nodes in the tree.
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.
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Sum of all leaf nodes of binary tree
- Count Non-Leaf nodes in a Binary Tree
- Pairwise Swap leaf nodes in a binary tree
- Print the nodes of binary tree as they become the leaf node
- Print all leaf nodes of a Binary Tree from left to right
- Maximum sum of leaf nodes among all levels of the given binary tree
- Print all leaf nodes of a binary tree from right to left
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Program to count leaf nodes in a binary tree
- Iterative program to count leaf nodes in a Binary Tree
- Print left and right leaf nodes separately in Binary Tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Print leaf nodes in binary tree from left to right using one stack
- Generate Complete Binary Tree in such a way that sum of non-leaf nodes is minimum
- Create Balanced Binary Tree using its Leaf Nodes without using extra space
- Find height of a special binary tree whose leaf nodes are connected
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Product 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.