--- tags: leetcode --- # [113. Path Sum II](https://leetcode.com/problems/path-sum-ii/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * 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: vector<vector<int>> pathSum(TreeNode *root, int targetSum) { vector<int> path; dfs(root, path, targetSum); return answer; } private: vector<vector<int>> answer; void dfs(TreeNode *root, vector<int> &path, int targetSum) { if (root == nullptr) { return; } path.push_back(root->val); if (root->left == nullptr && root->right == nullptr && root->val == targetSum) { answer.push_back(path); } dfs(root->left, path, targetSum - root->val); dfs(root->right, path, targetSum - root->val); path.pop_back(); } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree referred by `root`. ## Space Complexity $O(H)$ $H$ is the height of the binary tree referred by `root`. # Miscellane <!-- # Test Cases ``` [5,4,8,11,null,13,4,7,2,null,null,5,1] 22 ``` ``` [1,2,3] 5 ``` ``` [1,2] 0 ``` ``` [5,4,8,11,null,13,4,7,2,null,null,null,1] 22 ``` ``` [1,2] 1 ``` ``` [-2,6,null,0,-6] 4 ``` -->