https://leetcode.com/problems/path-sum-iii/
1. Use recusion:
//28 ms 15.7 MB/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/class Solution {public://sum of pathsint pathSum(TreeNode* root, int sum) {if (!root) return 0;return numberOfPaths(root, sum) +pathSum(root->left, sum) +pathSum(root->right, sum);}private://number of paths origniated by rootint numberOfPaths(TreeNode* root, int sum) {if (!root) return 0;sum -= root->val;if(sum == 0)return 1 + numberOfPaths(root->left, sum) + numberOfPaths(root->right, sum);return numberOfPaths(root->left, sum) + numberOfPaths(root->right, sum);}};
