Find the sum of all left leaves in a given binary tree.

Example:

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

O(n) time O(n) space iterative BFS solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int sum = 0;
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur.left != null && cur.left.left == null && cur.left.right == null) {
sum += cur.left.val;
} else if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
return sum;
}
}

O(n) time O(n) space DFS recursive solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) return 0;
int left = 0, right = 0;
if (root.left != null) {
if (root.left.left == null && root.left.right == null) {
left = root.left.val;
} else {
left = sumOfLeftLeaves(root.left);
}
}
if (root.right != null) {
right = sumOfLeftLeaves(root.right);
}
return left + right;
}
}