leetcode 路径总和II 中等

 

 

直接 dfs 遍历提前判断叶子结点就行了,没特别的。

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<int> path;
        solve(root, targetSum, path, 0);
        return ret;
    }

private:
    vector<vector<int>> ret;
    void solve(TreeNode *root, const int &target, vector<int> &path, int sum) {
        if(!root) return;
        sum += root -> val;
        path.emplace_back(root -> val);
        if(!root -> left && !root -> right) {   // 叶子
            if(sum == target) ret.emplace_back(path);
            path.pop_back();
            sum -= root -> val;
            return ;
        }
        solve(root -> left, target, path, sum);
        solve(root -> right, target, path, sum);
        path.pop_back();
        sum -= root -> val;
    }
};

 

posted @ 2021-09-20 11:28  rookie_Acmer  阅读(21)  评论(0编辑  收藏  举报