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.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sum=0;
public int sumOfLeftLeaves(TreeNode root) {
if(root==null)return 0;
leftcheck(root,0);
return sum;
}
public int leftcheck(TreeNode root,int i){
if(i==1&&root.left==null&&root.right==null)sum+=root.val;
if(root.left!=null){
int l=leftcheck(root.left,1);//如果写成sum+=leftcheck(root.left,1);这里就会出错,原因嘛,编译器的问题吧,拆开写反而没有问题,当然和这道题无关
//sum+=l;
}
if(root.right!=null)leftcheck(root.right,0);
return root.val;
}
}
另一种方法就是写一个验证是否是左叶子节点的函数
boolean isleft(root){
if(root.left==null&&root.right==null)
return true;
return false;
}
使用的时候isleft(root.left);