leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0113.cpp (802B)


      1 class Solution {
      2   public:
      3     vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
      4         if (!root) return {};
      5         stack<pair<TreeNode *, int>> st;
      6         vector<vector<int>> res;
      7         vector<int> path;
      8         st.push({root, 0});
      9         while (!st.empty()) {
     10             auto [root, sum] = st.top();
     11             if (sum == INT_MIN) {
     12                 st.pop();
     13                 path.pop_back();
     14                 continue;
     15             }
     16             sum += root->val;
     17             st.top().second = INT_MIN;
     18             path.push_back(root->val);
     19 
     20             if (!root->left && !root->right && sum == targetSum) res.push_back(path);
     21             if (root->left) st.push({root->left, sum});
     22             if (root->right) st.push({root->right, sum});
     23         }
     24         return res;
     25     }
     26 };