https://leetcode.com/problems/path-sum-iii/

1. Use recusion:

  1. //28 ms 15.7 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  10. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  11. * };
  12. */
  13. class Solution {
  14. public:
  15. //sum of paths
  16. int pathSum(TreeNode* root, int sum) {
  17. if (!root) return 0;
  18. return numberOfPaths(root, sum) +
  19. pathSum(root->left, sum) +
  20. pathSum(root->right, sum);
  21. }
  22. private:
  23. //number of paths origniated by root
  24. int numberOfPaths(TreeNode* root, int sum) {
  25. if (!root) return 0;
  26. sum -= root->val;
  27. if(sum == 0)
  28. return 1 + numberOfPaths(root->left, sum) + numberOfPaths(root->right, sum);
  29. return numberOfPaths(root->left, sum) + numberOfPaths(root->right, sum);
  30. }
  31. };