# Get the Sum of all left leaves in a Binary tree

Objective: Given a binary tree, find the sum of all the nodes which are left as well as leaves nodes.

Example: Get the Sum of all left leaves in a Binary tree.

Approach:

1. Approach is quite simple.
2. Do the inorder traversal
3. check if node if the left child and leaf node.
4. If yes then add it to the sum.
5. See the code for more understanding.

Complete Code:

 public class LeftLeavesSum { // Do the inorder traversal // check if node if the left child and leaf node // if yes then add it to the sum public static int leftLeavesSum = 0; public static void leftSum(Node root, Node parent) { if (root != null) { leftSum(root.left, root); if (root.left == null && root.right == null && parent.left == root) { leftLeavesSum += root.data; } leftSum(root.right, root); } } public static void main(String args[]) { Node root = new Node(10); root.left = new Node(5); root.right = new Node(15); root.left.left = new Node(10); root.left.right = new Node(12); root.left.right.left = new Node(6); root.right.right = new Node(8); root.right.right.left = new Node(5); leftSum(root, root); System.out.println("Sum of left leaves: " + leftLeavesSum); } } class Node { int data; Node left; Node right; public Node(int data) { this.data = data; this.left = null; this.right = null; } }

view raw
LeftLeavesSum.java
hosted with ❤ by GitHub

Output:

```Sum of left leaves: 21
```

### 1 thought on “Get the Sum of all left leaves in a Binary tree”

1. Traverse given binary tree using pre order traversal. If current node is left leaf node, then add it’s value to variable sum of left node of binary tree. If current node is not a left leaf node then recursively calculate the sum of left leaf nodes of binary tree in left and right sub tree and return.