When I updated the above question, I wondered if there was another print path.
This kind of question is very common, and the practice is very simple. I use a referenced vector to store it. After the conditions are met, it is directly pushed into the result set. Of course, arrays and the like can also be used. It is worth noting that recursion will affect the upper-layer status in the stack. Of course, the value passing method can be used to avoid this problem, however, it is too costly (it is not a wise choice to build and destroy a Class Object each time ). So it is to roll back. When and how many times? I think it can be determined that, in a layer of recursion, the push and pop-up will appear in pairs. When the method is pressed several times, it will pop up several times. The press-in is probably performed at the beginning of the method, and the pop-up is probably performed at the end of the method. The end of the method not only indicates that the method exits at the end of the method, it is also possible that the returned results are displayed when you find that the stored results of this reference meet a certain condition or are sure that the results do not meet a certain condition.
bool getPath(TreeNode *root, int sum, int tpsum, vector<vector<int> > &res, vector<int> &tpres){ if(root == NULL) return false; tpsum += root->val; tpres.push_back(root->val); if(!root->left && !root->right){ if(tpsum == sum){ res.push_back(tpres); tpres.pop_back(); return true; }else{ tpres.pop_back(); return false; } } bool ret = false; if(root->left) ret |= getPath(root->left, sum, tpsum, res, tpres); if(root->right) ret |= getPath(root->right, sum, tpsum, res, tpres); tpres.pop_back(); return ret;}class Solution {public: vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > res; if(root == NULL) return res; vector<int> tpres; getPath(root, sum, 0, res, tpres); return res; }};