題目描述
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
代碼
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> curs;
dfs(root, curs, sum, 0, res);
return res;
}
void dfs(TreeNode* root, vector<int>& curs, int sum, int cur, vector<vector<int>>& res) {
if (root == NULL) return;
if (root->left == NULL && root->right == NULL && cur+root->val == sum) {
curs.push_back(root->val);
vector<int> tmp(curs.begin(), curs.end());
curs.pop_back();
res.push_back(tmp);
return;
}
if (root->left) {
curs.push_back(root->val);
dfs(root->left, curs, sum, cur+root->val, res);
curs.pop_back();
}
if (root->right){
curs.push_back(root->val);
dfs(root->right, curs, sum, cur+root->val, res);
curs.pop_back();
}
return;
}
};