404 Sum of Left Leaves

404. Sum of Left Leaves

1. Question

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 15respectively. Return 24.

2. Implementation

(1) BFS

思路:这里要注意left leaves的意思,首先必须一个node必须是另一个node的left children,其次这个node必然不是root,且它没有任何children才算leaves。所以在BFS的过程中,我们要检测curNode.left是否为空,如果不是的话再看curNode.left有没有任何children,如果没有则curNode.left是一个合格的left leave我们加上它的value

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

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        int sum = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();

                if (curNode.left != null) {
                    if (curNode.left.left == null && curNode.left.right == null) {
                        sum += curNode.left.val;
                    }
                }

                if (curNode.left != null) {
                    queue.add(curNode.left);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
        }
        return sum;
    }
}

(2) DFS:

思路:和BFS的思路差不多

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        int[] sum = new int[1];
        getSumOfLeftLeaves(root, sum);
        return sum[0];
    }

    public void getSumOfLeftLeaves(TreeNode node, int[] sum) {
        if (node == null) {
            return;
        }

        if (node.left != null) {
            if (node.left.left == null && node.left.right == null) {
                sum[0] += node.left.val;
            }
            else {
                getSumOfLeftLeaves(node.left, sum);
            }
        }
        getSumOfLeftLeaves(node.right, sum);
    }
}

3. Time & Space Complexity

BFS: 时间复杂度O(n), 空间复杂度:O(w), w为树的一层中拥有最多node的个数

DFS: 时间复杂度O(h), h是树的高度,空间复杂度: O(h)

Last updated