public int sumOfLeftLeaves(TreeNode root) {
int res = 0;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node != null) {
if (node.left != null && node.left.left == null && node.left.right == null)
res += node.left.val;
stack.push(node.left);
stack.push(node.right);
}
}
return res;
}
Java solution with Stack


We can also use queue.
public int sumOfLeftLeaves(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); int res = 0; TreeNode node = root; queue.offer(node); while(queue.size() != 0) { TreeNode head = queue.poll(); if (head!= null) { if ( head.left != null && head.left.left == null && head.left.right == null) { res += head.left.val; } queue.offer(head.left); queue.offer(head.right); } } return res; }