Sum of Left Leaves

weixin_33866037發表於2018-06-02

https://www.lintcode.com/problem/sum-of-left-leaves/description

/**
 * Definition of TreeNode:
 * public class TreeNode {
 * public int val;
 * public TreeNode left, right;
 * public TreeNode(int val) {
 * this.val = val;
 * this.left = this.right = null;
 * }
 * }
 */

public class Solution {
    private int sum = 0;
    /**
     * @param root: t
     * @return: the sum of all left leaves
     */
    public int sumOfLeftLeaves(TreeNode root) {
        // Write your code here
        tree(root, false);
        return sum;
    }

    private void tree(TreeNode root, boolean b) {
        if (root == null) {
            return;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        if (left == null && right == null) {
            if (b) {
                sum += root.val;
            }
        }
        tree(left, true);
        tree(right, false);
    }
}