1. Double Recursion (Check From Every Node)
Intuition
1. Helper countFrom(node, sum): counts paths starting strictly at node. 2. Main pathSum(root, sum): return countFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum).
When to apply: Basic baseline check.
Algorithm
- Step 1: Helper countFrom(node, rem): if null return 0; count = (node.val == rem) ? 1 : 0.
- Step 2: count += countFrom(node.left, rem - node.val) + countFrom(node.right, rem - node.val).
- Step 3: Main function: countFrom(root, target) + pathSum(root.left, target) + pathSum(root.right, target).
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution { int countFrom(TreeNode* node, long long sum) { if (!node) return 0; int count = (node->val == sum) ? 1 : 0; count += countFrom(node->left, sum - node->val); count += countFrom(node->right, sum - node->val); return count; }public: int pathSum(TreeNode* root, int targetSum) { if (!root) return 0; return countFrom(root, targetSum) + pathSum(root->left, targetSum) + pathSum(root->right, targetSum); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n^2)— On skewed trees, visits each subtree from every ancestor. - Space complexity:
O(h)— Call stack bounded by tree height h.