Given a Binary tree. The task is to find and print the product and sum of all internal nodes (non-leaf nodes) in the tree.
In the above tree, only two nodes 1 and 2 are non-leaf nodes.
Therefore, product of non-leaf nodes = 1 * 2 = 2.
And sum of non-leaf nodes = 1 + 2 =3.
Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Product = 36, Sum = 12 Non-leaf nodes are: 1, 2, 3, 6
Approach: The idea is to traverse the tree in any fashion and check if the current node is a non-leaf node or not. Take two variables product and sum to store the product and sum of non-leaf nodes respectively. If the current node is non-leaf node then multiply the node’s data to the variable product used to store the products of non-leaf nodes and add the node’s data to the variable sum used to store the sum of non-leaf nodes.
Below is the implementation of the above idea:
Product = 2 , Sum = 3
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.
- Product of all leaf nodes of binary tree
- Product of all nodes in a Binary Tree
- Print all nodes in a binary tree having K leaves
- Print all full nodes in a Binary Tree
- Print all internal nodes of a Binary tree
- Print Levels of all nodes in a Binary Tree
- Print all even nodes of Binary Search Tree
- Print all nodes between two given levels in Binary Tree
- Print all odd nodes of Binary Search 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 path from root to all nodes in a Complete Binary Tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
- Print alternate nodes from all levels of a Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Print leftmost and rightmost nodes of a Binary Tree
- Print left and right leaf nodes separately in 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.