LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
class Solution {
 public:
  int pathSum(TreeNode* root, int sum) {
    if (!root) {
      return 0;
    }
    int res = 0;
    dfs(root, res, sum);
    res += pathSum(root->left, sum);
    res += pathSum(root->right, sum);
    return res;
  }

  void dfs(TreeNode* root, int& res, int n) {
    if (!root) {
      return;
    }
    if (root->val == n) {
      ++res;
    }
    dfs(root->left, res, n - root->val);
    dfs(root->right, res, n - root->val);
  }
};