This topic DFS used very not confident.
(1) The use of recursion is not bold enough to consider the details, should stand higher.
(2) After the idea is clarified, notice the change of the state value, which is the state recovery. When the depth first goes to the end, it needs to be returned, and the corresponding state should return. For example, the state data that was put in the stack/vector is going to pop up.
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:void dfs (vector<vector<int>> &res,vector<int> &path,treenode * root, int sum) {if (!root) return; if (!root->left&&!root->right) {if (root->val==sum) {path.push_back (Root->val) ; Res.push_back (path); Path.pop_back (); } else return; } sum=sum-root->val; Path.push_back (Root->val); DFS (res,path,root->left,sum); Path.pop_back (); Path.push_back (Root->val); DFS (res,path,root->right,sum); Path.pop_back (); } vector<vector<int> > Pathsum (TreeNode *root, int sum) {vector<vector<int>> res; Vector<int> path; DFS (rEs,path,root,sum); return res; }};
A DFS solution that saves a tree root to a leaf and all paths for a given value