leetcode-----113. 路径总和 II

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ans;
    vector<int> path;

    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        if (root) dfs(root, sum);
        return ans;
    }

    void dfs(TreeNode* root, int sum) {
        path.push_back(root->val);
        sum -= root->val;
        if (!root->left && !root->right) {
            if (!sum) {
                ans.push_back(path);
            } 
        } else {
            if (root->left) dfs(root->left, sum);
            if (root->right) dfs(root->right, sum);
        }
        path.pop_back();
    }
};
posted @ 2020-07-26 14:17  景云ⁿ  阅读(56)  评论(0编辑  收藏  举报