题目:
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; }
* }
*/
class Solution {
public int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
tr(root, false);
return sum;
}
public void tr(TreeNode root, boolean isleft){
if(root == null) return;
else if(root.left == null && root.right == null && isleft){
sum += root.val;
}
else{
tr(root.left, true);
tr(root.right, false);
}
}
}