JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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.

Code

class Solution {
    int sum = 0;
    public int sumOfLeftLeaves(TreeNode root) {
        helper(root, false);
        return sum;
    }

    private void helper(TreeNode root, Boolean isLeft){
        if(root == null) return;

        if(root.left == null && root.right == null) {
            if(isLeft) {
                sum += root.val;
            }

            return;
        }

        helper(root.left, true);
        helper(root.right, false);
    }
}