113. Path Sum II
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]
]
思路
前一题和这一题是dfs的两种不同问题,Path Sum是求是否存在解,这一题是求所有解,所以很简单,把所有的解都记录下来即可。
C++11
/**
* 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>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
dfs(root, sum, vector<int>{}, res);
return res;
}
void dfs(TreeNode* root, int sum, vector<int> path, vector<vector<int>> &res) {
if (root == NULL) return;
path.emplace_back(root->val);
if (root->left == NULL and root->right == NULL and root->val == sum) res.emplace_back(path);
if (root->left) dfs(root->left, sum - root->val, path, res);
if (root->right) dfs(root->right, sum - root->val, path, res);
}
};