![]() |
VOOZH | about |
Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6.
The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then add it to the result.
Following is the implementation of the above idea.
Sum of left leaves is 78
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of given binary tree due to recursion call.
Following is Another Method to solve the above problem. This solution passes in a sum variable as an accumulator. When a left leaf is encountered, the leaf's data is added to sum. Time complexity of this method is also O(n). Thanks to Xin Tong (geeksforgeeks userid trent.tong) for suggesting this method.
Sum of left leaves is 78
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of given binary tree due to recursion call.
Following is Another Method to solve the above problem. We can pass bool as parameter in the function to check if it is a left or right node. Time complexity of this method is also O(n).
Sum of left leaves is: 78
Iterative Approach :
This is the Iterative Way to find the sum of the left leaves.
Idea is to perform Depth-First Traversal on the tree (either Inorder, Preorder or Postorder) using a stack and checking if the Left Child is a Leaf node. If it is, then add the nodes value to the sum variable
Sum of left leaves is 78
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of given binary tree.
Thanks to Shubham Tambere for suggesting this approach.
BFS Approach: We can do BFS traversal and keep a separate variable for denoting if it is a left child or right child of a node. As soon as we encounter a leaf, we check if it is a left child of its parent or right child of its parent. If it is a left child, we add its value in the sum.
Below is the implementation of the above approach:
Sum of left leaves is 78
Time Complexity: O(N)
Auxiliary Space: O(N)