Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
Solution:
Method 1: Iterative
We use pre-order traversal.
At any node, if we want to push its left child to the stack, we check if this left child's left child is a left leaf.
If it is, we add its value.
We push a right child into the stack only if this right child has child. (There might be left leaf in this subtree.)
Code:
/** * 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) { int sum = 0; if (root == null) { return sum; } Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { root = stack.pop(); if (root.right != null) { if (root.right.left != null || root.right.right != null) { stack.push(root.right); } } if (root.left != null) { if (root.left.left == null && root.left.right == null) { sum += root.left.val; } else { stack.push(root.left); } } } return sum; } }
Method 2: Recursive
From root, we sum up all its left subtree's left leaves.
Then we add its right subtree's left leaves.
Code:
/** * 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) { return 0; } int sum = 0; if (root.left != null) { if (root.left.left == null && root.left.right == null) { sum += root.left.val; } else { sum += sumOfLeftLeaves(root.left); } } sum += sumOfLeftLeaves(root.right); return sum; } }