404-Sum of Left Leaves

kevin聰發表於2018-04-30

Description

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.

問題描述

求出二叉樹的所有左葉子的值的和


問題分析


解法

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return sumOfLeftLeavesHelper(root, false);
    }

    private int sumOfLeftLeavesHelper(TreeNode root, boolean cameFromLeft) {
        if (root == null) return 0;

        if (root.left == null && root.right == null) return cameFromLeft ? root.val : 0;

        return 0 + sumOfLeftLeavesHelper(root.left, true) + sumOfLeftLeavesHelper(root.right, false);
    }
}

相關文章