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.
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.
- Boundary Traversal of binary tree
- Iterative Boundary Traversal of Complete Binary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Boundary Level order traversal of a Binary Tree
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Count of all prime weight nodes between given nodes in the given Tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Sum of all nodes in a binary tree
- Find sum of all nodes of the given perfect binary tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Sum of all the child nodes with even parent values in a Binary Tree
- Sum of all nodes at Kth level in a Binary Tree
- Sum of all leaf nodes of binary tree
- Sum of all the child nodes with even grandparents in a Binary Tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Sum of heights of all individual nodes in a binary tree
- Check if all nodes of the Binary Tree can be represented as sum of two primes
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.