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.
求树的所有左叶子的和
public class SumofLeftLeaves {
public int sumOfLeftLeaves(TreeNode root) {
int sum = 0;
if (root == null)
return 0;
if (isLeave(root.left))
sum += root.left.val;
sum += sumOfLeftLeaves(root.left);
sum += sumOfLeftLeaves(root.right);
return sum;
}
public boolean isLeave(TreeNode node) {
if (node == null)
return false;
if (node.left == null && node.right == null)
return true;
return false;
}
}