Leetcode|二叉树的属性DFS回溯|113. 路径总和 II

2022-01-10 15:11:35 浏览数 (1)

《Leetcode|二叉树的属性|112. 路径总和》

《Leetcode|二叉树的属性DFS回溯|113. 路径总和 II》

1 DFS回溯

代码语言:javascript复制
/**
 * 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>> res;
    vector<int> path;

    void backtrack(TreeNode* root, int targetSum) {
        if (!root) return;
        if (!root->left && !root->right) {
            if (targetSum == root->val) {
                path.push_back(root->val);
                res.push_back(path);
                path.pop_back();
            }
            return;
        }
        path.push_back(root->val);
        backtrack(root->left, targetSum - root->val);
        backtrack(root->right, targetSum - root->val);
        path.pop_back();
    }

    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        if (!root) return {};
        backtrack(root, targetSum);
        return res;
    }
};

0 人点赞