240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 15 | Leetcode 113. Path Sum II

题解

Medium | DFS

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> paths;
        vector<int> path;
        
        dfs(root, sum, path, paths);
        
        return paths;
    }
    
    void dfs(TreeNode* node, int sum, vector<int> path, vector<vector<int>>& paths) {
        if(!node) {
            return;
        }

        path.push_back(node->val);
        
        if(!node->left && !node->right && node->val == sum) {
            paths.push_back(path);
            return;
        }

        dfs(node->left, sum - node->val, path, paths);
        dfs(node->right, sum - node->val, path, paths);
    }
};
posted @ 2020-09-30 14:44  CasperWin  阅读(60)  评论(0编辑  收藏  举报