1 vector<vector<int>> pathSum(TreeNode* root,int sum){//DFS遍历获取适合路径,当递归到叶子结点且sum为0,表示该路径合适 2 vector<vector<int>> ans; 3 vector<int> path; 4 5 helper(root,ans,path,sum); 6 return ans; 7 } 8 void helper(TreeNode* root,vector<vector<int>>& ans,vector<int>& path,int sun){ 9 if(root == NULL) return; 10 sum -= root->val; 11 path.push_back(root->val); 12 if(!root->right && !root->left && !sum) ans.push_back(path); 13 helper(root->left,ans,path,sum); 14 helper(root->right,ans,path,sum); 15 path.pop_back();//当该路径不合适,将末尾节点弹出,回溯到上一个节点有节点 16 }