1. All Root-to-Leaf Path Accumulation
Intuition
Traverse tree collecting sum of every root-to-leaf path into a vector. Check if targetSum exists in vector.
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return false.
- Step 2: Collect all leaf sums using helper dfs(node, curSum, sums).
- Step 3: Check if targetSum is contained in sums list.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void getSums(TreeNode* node, int cur, vector<int>& sums) { if (!node) return; cur += node->val; if (!node->left && !node->right) { sums.push_back(cur); return; } getSums(node->left, cur, sums); getSums(node->right, cur, sums); } bool hasPathSum(TreeNode* root, int targetSum) { if (!root) return false; vector<int> sums; getSums(root, 0, sums); for (int s : sums) if (s == targetSum) return true; return false; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Traverses all nodes and stores all leaf sums. - Space complexity:
O(n)— List stores sums of all leaf nodes.