Given a binary tree, the task is to find the sum of the nodes which are visible in the left view. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left.
Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 7 1 + 2 + 4 = 7 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 18
Approach: The problem can be solved using simple recursive traversal. We can keep track of the level of a node by passing a parameter to all the recursive calls. The idea is to keep track of the maximum level also and traverse the tree in a manner that the left subtree is visited before the right subtree. Whenever a node whose level is more than the maximum level so far is encountered, add the value of the node to the sum because it is the first node in its level (Note that the left subtree is traversed before the right subtree).
Below is the implementation of the above approach:
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.
- Sum of nodes in the right view of the given binary tree
- Iterative Method To Print Left View of a Binary Tree
- Print Left View of a Binary Tree
- Sum of nodes in top view of binary tree
- Sum of nodes in bottom view of Binary Tree
- Check if the Left View of the given tree is sorted or not
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Print Nodes in Top View of Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Print nodes in top view of Binary Tree | Set 2
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print leaf nodes in binary tree from left to right using one stack
- Print all leaf nodes of a binary tree from right to left
- Print left and right leaf nodes separately in Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
- Connect all nodes to their Left Neighbors in a Binary Tree
- Find sum of all left leaves in a given Binary Tree
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count of all prime weight nodes between given nodes in the given Tree
- Construct XOR tree by Given leaf nodes of Perfect 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.