Easy
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.
9ms:
public int sumOfLeftLeaves(TreeNode root) {
if(root==null)
return 0;
int i = 0;
if(root.left!=null)
i = subSum(i,true,root.left);
if(root.right!=null)
i = subSum(i,false,root.right);
return i;
}
private int subSum(int i,boolean left,TreeNode node){
if(node.left==null&&node.right==null)
return left?(i+node.val):i;
if(node.left!=null)
i = subSum(i,true,node.left);
if(node.right!=null)
i = subSum(i,false,node.right);
return i;
}
优化格式:
public int sumOfLeftLeaves(TreeNode node) {
return node == null ? 0 : sumOfLeftLeaves(node, false);
}
private int sumOfLeftLeaves(TreeNode node, boolean isLeft) {
return node.left == null && node.right == null ? isLeft ? node.val : 0 : ((node.left == null ? 0 : sumOfLeftLeaves(node.left, true)) + (node.right == null ? 0 : sumOfLeftLeaves(node.right, false)));
}