Topic
answer
We only need to traverse all the paths, and then find the matching path, pay attention to restore the state after each recursion is completed
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void dfs(TreeNode *root, int sum) {
if (!root) return;
sum -= root->val;
path.push_back(root->val);
if (!root->left && !root->right && !sum) {
res.push_back(path);
}
dfs(root->left, sum);
dfs(root->right, sum);
path.pop_back(); //还原状态
}
vector<vector<int>> findPath(TreeNode *root, int sum) {
dfs(root, sum);
return res;
}
};