找到所有左侧叶子结点的和。
稍微改变一下递归链,我们不递归右边的叶子结点,还有这个函数对于root是leaf的时候需要特殊判断
/**
* 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(isLeaf(root)) return 0;
return search_left_leaves(root);
}
private int search_left_leaves(TreeNode root)
{
if(root==null) return 0;
if(isLeaf(root)) return root.val;
int left = 0 ;
int right= 0 ;
left=search_left_leaves(root.left);
if(!isLeaf(root.right))
right=search_left_leaves(root.right);
return left+right;
}
private boolean isLeaf(TreeNode root)
{
if(root==null) return false;
return root.left==null&&root.right==null;
}
}