← Home

113. Path Sum II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
113

The trick here is to name the state correctly, then let the implementation follow. For 113. Path Sum II, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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, backtracking.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • 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:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. 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

solution.cpp
01//Runtime: 8 ms, faster than 96.37% of C++ online submissions for Path Sum II.
02//Memory Usage: 20.5 MB, less than 10.12% of C++ online submissions for Path Sum II.
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 *     int val;
07 *     TreeNode *left;
08 *     TreeNode *right;
09 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
10 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12 * };
13 */
14class Solution {
15public:
16    vector<vector<int>> ans;
17    int sum;
18    
19    void backtrack(TreeNode* cur, vector<int>& path){
20        //cur must not be nullptr
21        //when entering this function, cur is added in "path"
22        if(!cur->left && !cur->right){
23            // for(const int& e : path) cout << e << " ";
24            // cout << endl;
25            if(accumulate(path.begin(), path.end(), 0) == sum){
26                ans.push_back(path);
27            }
28        }else{
29            if(cur->left){
30                path.push_back(cur->left->val);
31                backtrack(cur->left, path);
32                path.pop_back();
33            }
34            
35            if(cur->right){
36                path.push_back(cur->right->val);
37                backtrack(cur->right, path);
38                path.pop_back();
39            }
40        }
41    }
42    
43    vector<vector<int>> pathSum(TreeNode* root, int sum) {
44        if(!root) return vector<vector<int>>();
45        
46        this->sum = sum;
47        
48        vector<int> path = {root->val};
49        backtrack(root, path);
50        
51        return ans;
52    }
53};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.