程式語言 - LeetCode - C++ - 113. Path Sum II



題目:


解答:

/**
 * 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> q;
        vector<vector<int>> ans;

        auto dfs = [&](this auto&& dfs, TreeNode* root, int targetSum) -> void {
            if (!root) {
                return;
            }

            q.push_back(root->val);

            if (!root->left && !root->right && targetSum == root->val) {
                ans.push_back(q);
            }

            dfs(root->left, targetSum - root->val);
            dfs(root->right, targetSum - root->val);
            q.pop_back();
        };

        dfs(root, targetSum);
        return ans;
    }
};