1. Pass Path by Value Recursion
Intuition
Pass path vector by value to children. When reaching a matching leaf, add path to result list.
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return.
- Step 2: Append root.val to path copy.
- Step 3: If leaf and targetSum == root.val, append path to res.
- Step 4: Recurse left and right passing path copy.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void dfs(TreeNode* node, int sum, vector<int> path, vector<vector<int>>& res) { if (!node) return; path.push_back(node->val); if (!node->left && !node->right && node->val == sum) { res.push_back(path); return; } dfs(node->left, sum - node->val, path, res); dfs(node->right, sum - node->val, path, res); } vector<vector<int>> pathSum(TreeNode* root, int targetSum) { vector<vector<int>> res; dfs(root, targetSum, {}, res); return res; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n * h)— Copying path arrays of size up to h at each node. - Space complexity:
O(n * h)— Stack frames hold full copies of paths.