LeetCode Path Sum II

class Solution {
private:
    vector<vector<int> > result;
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        result.clear();
        vector<int> path;
        dfs(root, path, sum);
        return result;
    }
    
    void dfs(TreeNode *root, vector<int>& path, int sum) {
        if (root == NULL) return;
        if (root->left == NULL && root->right == NULL && root->val == sum) {
            path.push_back(root->val);
            result.push_back(path);
            path.pop_back();
            return;
        }
        path.push_back(root->val);
        dfs(root->left, path, sum - root->val);
        dfs(root->right, path, sum - root->val);
        path.pop_back();
    }
};

水一发

posted @ 2014-04-23 22:05  卖程序的小歪  阅读(167)  评论(0编辑  收藏  举报