404. Sum of Left Leaves (Easy)

https://leetcode.com/problems/sum-of-left-leaves/

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.

Solutions

class Solution {

    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }

        List<TreeNode> lleafs = new ArrayList<>();
        dfs(root, lleafs);

        int ans = 0;
        for (TreeNode leaf : lleafs) {
            ans += leaf.val;
        }

        return ans;
    }

    private void dfs(TreeNode root, List<TreeNode> lleafs) {
        if (root == null) {
            return;
        }

        if (root.left != null && root.left.left == null && root.left.right == null) {
            lleafs.add(root.left);
        } else {
            dfs(root.left, lleafs);
        }

        dfs(root.right, lleafs);
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-07-03 00:26:46

results matching ""

    No results matching ""