Given a binary tree, the task is to print the sum of nodes in bottom view of the given Binary Tree. Bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom.
Input : 1 / \ 2 3 / \ \ 4 5 6 Output : 20 Input : 1 / \ 2 3 \ 4 \ 5 \ 6 Output : 17
Approach: The idea is to use a queue.
- Put tree nodes in a queue for the level order traversal
- Start with the horizontal distance(hd) 0 of the root node, keep on adding left child to queue along with the horizontal distance as hd-1 and right child as hd+1.
- Use a map to store the hd value(as key) and the last node(as pair) having the corresponding hd value.
- Every time, we encounter a new horizontal distance or an existing horizontal distance put the node data for the horizontal distance as key. For the first time it will add to the map, next time it will replace the value. This will make sure that the bottom most element for that horizontal distance is present in the map.
- Finally, traverse the map and calculate the sum of all of the elements.
Below is the implementation of the above approach:
- Bottom View of a Binary Tree
- Bottom View of a Binary Tree using Recursion
- Print Bottom-Right View of a Binary Tree
- Sum of nodes in the right view of the given binary tree
- Sum of nodes in top view of binary tree
- Print nodes in top view of Binary Tree | Set 2
- Print nodes in the Top View of Binary Tree | Set 3
- Sum of nodes in the left view of the given binary tree
- Print Nodes in Top View of Binary Tree
- Right view of Binary Tree using Queue
- Print Right View of a Binary Tree
- Print Left View of a Binary Tree
- Iterative Method To Print Left View of a Binary Tree
- Sum of all nodes in a binary tree
- 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 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 : rituraj_jain