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.
递归,如果root为null,返回0.如果左子节点是leave,返回(左子节点值 + 对右子树的递归),否则返回左右子树递归调用结果之和。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null)
return 0;
int sum = 0;
if(isLeave(root.left)) {
sum += root.left.val;
} else {
sum += sumOfLeftLeaves(root.left);
}
int right = sumOfLeftLeaves(root.right);
return sum + right;
}
public boolean isLeave(TreeNode root) {
if(root == null)
return false;
return root.left == null && root.right == null;
}
}