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.
思路:
满足条件的node要有两个属性:
1. 是最左点。
2. 而且最左点没有左右孩子,表明是leave。
/**
* 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) {
int[] res = {0};
sumLeftLeavesHelper(root, res);
return res[0];
}
public void sumLeftLeavesHelper(TreeNode root, int[] res){
if(root == null){
return;
}
if(root.left!=null && root.left.left == null && root.left.right == null){
res[0] += root.left.val;
}
sumLeftLeavesHelper(root.left, res);
sumLeftLeavesHelper(root.right, res);
}
}