I like to read this solution as a small machine: keep the useful information, throw away the noise. For 404. Sum of Left Leaves, the solution in this repository is mainly a two pointers solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: two pointers.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are rSumOfLeftLeaves, sumOfLeftLeaves.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Find the sum of all left leaves in a given binary tree.
03
04Example:
05
06 3
07 / \
08 9 20
09 / \
10 15 7
11
12There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
13**/
14
15//Runtime: 8 ms, faster than 100.00% of C++ online submissions for Sum of Left Leaves.
16//Memory Usage: 13.5 MB, less than 100.00% of C++ online submissions for Sum of Left Leaves.
17/**
18 * Definition for a binary tree node.
19 * struct TreeNode {
20 * int val;
21 * TreeNode *left;
22 * TreeNode *right;
23 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
24 * };
25 */
26class Solution {
27public:
28 int ans;
29
30 void rSumOfLeftLeaves(TreeNode* node, bool isLeft){
31 // cout << node->val << " " << isLeft << endl;
32 if(node->left == NULL && node->right == NULL && isLeft){
33 ans += node->val;
34 }
35 if(node->left){
36 rSumOfLeftLeaves(node->left, true);
37 }
38 if(node->right){
39 rSumOfLeftLeaves(node->right, false);
40 }
41 }
42
43 int sumOfLeftLeaves(TreeNode* root) {
44 if(root == NULL) return 0;
45
46 ans = 0;
47 rSumOfLeftLeaves(root, false);
48
49 return ans;
50 }
51};
Cost