递归
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @param sum int整型 * @return int整型vector<vector<>> */ vector<vector<int>> res; vector<int> vec; int target; void helper(TreeNode* root, int sum){ if(root == NULL) return; sum += root -> val; vec.push_back(root -> val); if(sum == target){ if(root -> left == NULL && root -> right == NULL) res.push_back(vec); }//这里注意节点的值可能为负数,所以不能提前终止! helper(root -> left, sum); helper(root -> right, sum); vec.pop_back(); } vector<vector<int> > pathSum(TreeNode* root, int sum) { // write code here target = sum; helper(root, 0); return res; } };