Given a binary tree, the task is to print the sum of all the boundary nodes of the tree.
Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 28 Input: 1 / \ 2 3 \ / 4 5 \ 6 / \ 7 8 Output: 36
Approach: We have already discussed the Boundary Traversal of a Binary tree. Here we will find the sum of the boundary nodes of the given binary tree in four steps:
- Sum up all the nodes of the left boundary,
- Sum up all the leaf nodes of the left sub-tree,
- Sum up all the leaf nodes of the right sub-tree and
- Sum up all the nodes of the right boundary.
We will have to take care of one thing that nodes don’t add up again, i.e. the left most node is also the leaf node of the tree.
Below is the implementation of the above approach:
Time Complexity: O(N) where N is the number of nodes in the binary tree.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Boundary Traversal of binary tree
- Iterative Boundary Traversal of Complete Binary tree
- Boundary Level order traversal of a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Sum of all nodes in a binary tree
- Sink Odd nodes in Binary Tree
- Sum of nodes in top view of binary tree
- Sum of all nodes at Kth level in a Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Sum of nodes in the right view of the given binary tree
- Sink even nodes in Binary Tree
- Sum of all leaf nodes of binary tree
- Product of all nodes in a Binary Tree
- Print all internal 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.