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
- Product of all nodes in a Binary Tree
- Product of all leaf nodes of binary tree
- Print Nodes in Top View of Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Print all even nodes of Binary Search Tree
- Print path between any two nodes in a Binary Tree
- Print all odd nodes of Binary Search Tree
- Print Levels of all nodes in a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Print all internal nodes of a Binary tree
- Print nodes in top view of Binary Tree | Set 2
- Print all full nodes in a Binary Tree
- Print all nodes in a binary tree having K leaves
- Print all leaf nodes of a binary tree from right to left
- Print leftmost and rightmost nodes of 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 email@example.com. 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 : SHUBHAMSINGH10