topic:
Given a binary tree and a goal sum, find all the paths whose sum of paths from the root node to the leaf node is equal to the given goal sum.
Explanation: A leaf node refers to a node without child nodes.
solution
Recursion
Recursively backtrack, record the value of count, when count==0, find the path, push_back
defines an additional array path for the res array, which is recorded as the path,
Code
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
void traversal(TreeNode* node, int count) {
if(node->left == NULL && node->right == NULL && count == 0) {
res.push_back(path);
return;
}
if(!node->left && !node->right) {
return;
}
if (node->left) {
path.push_back(node->left->val);
count -= node->left->val;
traversal(node->left, count);
path.pop_back();
count += node->left->val;
}
if (node->right) {
path.push_back(node->right->val);
count -= node->right->val;
traversal(node->right, count);
path.pop_back();
count += node->right->val;
}
return;
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
res.clear();
path.clear();
if (!root) return res;
path.push_back(root->val);
traversal(root, targetSum - root->val);
return res;
}
};