直接 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; } };