Leetcode 404. Sum of Left Leaves
Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of its parent.
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) {}
};
We’ll use a recursive depth-first search (DFS) approach to traverse the binary tree. At each node, we’ll check if the left child is a leaf. If it is, we’ll add its value to our sum. We also need to continue traversing both left and right subtrees to ensure we capture all left leaves in the tree.
nullptr
, return 0.nullptr
) and the boolean indicates it is a left child, return the node value.false
(since the root is not a left child).#include <iostream>
// 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:
int sumOfLeftLeaves(TreeNode* root) {
return dfs(root, false);
}
private:
int dfs(TreeNode* node, bool isLeft) {
if (!node) return 0;
if (!node->left && !node->right) {
if (isLeft) return node->val; // only include left leaves
return 0;
}
return dfs(node->left, true) + dfs(node->right, false);
}
};
The time complexity is (O(n)), where (n) is the number of nodes in the tree. This is because in the worst case, we have to visit every node once.
The space complexity is (O(h)), where (h) is the height of the tree. This is due to the recursion stack for a DFS, which can vary from (O(\log n)) in a balanced tree to (O(n)) in the worst case (skewed tree).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?