404. Sum of Left Leaves

Sum of Left Leaves of a binary tree.

Given the root of a binary tree, return the sum of all left leaves.

Intuition

Use DFS to iterate over all nodes, if it is a left leaf, sum it to the result.

Approach

For every node, we care about one thing: whether its left child is a leaf node or not. If it is, then we add it.

Complexity

  • Time complexity: iterate all nodes once. $$ O(n) $$

  • Space complexity: Store the sum. $$ O(1) $$

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool is_leaf_node(TreeNode* node) {
        if (!node)  return false;
        return !(node->left || node->right);
    }

    int sumOfLeftLeaves(TreeNode* root) {
        if (!root)  return 0;
        int result = 0;
        if (is_leaf_node(root->left)) {
            result += root->left->val;
        }
        result += sumOfLeftLeaves(root->right);
        result += sumOfLeftLeaves(root->left);
        return result;
    }
};
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy