计算给定二叉树的所有左叶子之和
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return sum;
}
// 判断是否是左叶子节点
if (root.left != null && (root.left.left == null && root.left.right == null)) {
sum = sum + root.left.val;
}
sumOfLeftLeaves(root.left);
sumOfLeftLeaves(root.right);
return sum;
}
}