剑指offer 34:二叉树中和为某一值的路径

在这里插入图片描述

class Solution {
    
    
public:
    vector<vector<int>> res;
    vector<int> path;
    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) {
    
    
            if (root->val == targetSum) {
    
    
                res.push_back(path);
                return;
            }
        }
        dfs(root->left, path, targetSum - root->val);
        dfs(root->right, path, targetSum - root->val);
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
    
    
        dfs(root, path, targetSum);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/114026717
今日推荐