计算给定二叉树的所有左叶子之和。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/*
只求左叶子节点的和
1.判断一个节点是不是左叶子节点,是相加
*/
public int sumOfLeftLeaves(TreeNode root) {
if(root==null) return 0;
if(isLeaf(root.left)) return root.left.val+sumOfLeftLeaves(root.right);
return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
}
/*
判断一个节点是不是叶子节点
*/
public boolean isLeaf(TreeNode root){
if(root==null) return false;
return root.left==null&&root.right==null;
}
}