404. Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.

404. <wbr>Sum <wbr>of <wbr>Left <wbr>Leaves
Solution1 :Recursive递归,注意:left leaves是左子叶,终端节点才是叶节点。所以只有9和15计算在内
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;
    }
}
 
 
Solution2:
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null || root.left == null && root.right == null) {
            return 0;
        }
        int ans = 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            TreeNode tr = q.poll();
            if (tr.left != null && tr.left.left == null && tr.left.right == null) 
                 ans += tr.left.val;
            if (tr.left != null)
      q.offer(tr.left);
            if (tr.right != null)
      q.offer(tr.right);
        }
        return ans;
    }
}
posted @ 2019-03-15 16:08  MarkLeeBYR  阅读(173)  评论(0)    收藏  举报