A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1302. Deepest Leaves Sum, 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, sliding window.
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 deepestLeavesSum.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The queue gives the solution a level-by-level or frontier-style traversal.
- 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:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
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/*
02Runtime: 48 ms, faster than 73.18% of C++ online submissions for Deepest Leaves Sum.
03Memory Usage: 32.1 MB, less than 100.00% of C++ online submissions for Deepest Leaves Sum.
04*/
05
06/**
07 * Definition for a binary tree node.
08 * struct TreeNode {
09 * int val;
10 * TreeNode *left;
11 * TreeNode *right;
12 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
13 * };
14 */
15class Solution {
16public:
17 int deepestLeavesSum(TreeNode* root) {
18 int levelSum = 0, curLevelCount = 0, nextLevelCount = 0;
19 queue<TreeNode*> q;
20 TreeNode *node;
21
22 q.push(root);
23 curLevelCount++;
24
25 while(!q.empty()){
26 node = q.front(); q.pop();
27 curLevelCount--;
28 levelSum += node->val;
29
30 if(node->left){
31 q.push(node->left);
32 nextLevelCount++;
33 }
34
35 if(node->right){
36 q.push(node->right);
37 nextLevelCount++;
38 }
39
40 //go to next level
41 if(curLevelCount == 0){
42 curLevelCount = nextLevelCount;
43 nextLevelCount = 0;
44 //if there is still next level, clean levelSum
45 if(!q.empty()){
46 levelSum = 0;
47 }
48 }
49 }
50
51 return levelSum;
52 }
53};
Cost