BiruLyu
7/5/2017 - 8:49 PM

404. Sum of Left Leaves(1st).java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private void addLeftLeaves(TreeNode root, int[] res, boolean flag) {
        if (root == null) return;
        if (flag && root.left == null && root.right == null) res[0] += root.val; 
        if (root.left != null) addLeftLeaves(root.left, res, true);
        if (root.right != null) addLeftLeaves(root.right, res, false);
    }
    public int sumOfLeftLeaves(TreeNode root) {
        int[] res = new int[] {0};
        addLeftLeaves(root, res, false);
        return res[0];
    }
}
/**
 * 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 sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        
        int ans = 0;
        if(root.left != null){
            if(root.left.left == null && root.left.right == null)
                ans += root.left.val;
            else
                ans += sumOfLeftLeaves(root.left);
        }
        ans += sumOfLeftLeaves(root.right);
        return ans;
    }
}