问题描述:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
示例: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问题,将root到leaf路径上的和加起来与sum进行比较,相等则保留,不相等则不保留。
过程详见代码:
/**
* 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;
vector<int> re;
bl(root, res, re, sum);
return res;
}
void bl(TreeNode* root,vector<vector<int>> & res, vector<int>& re, int sum)
{
if (root == NULL) return;
if (root->val == sum && root->left == NULL && root->right == NULL)
{
re.push_back(root->val);
res.push_back(re);
re.pop_back();
return;
}
re.push_back(root->val);
bl(root->left, res, re, sum - root->val);
re.pop_back();
re.push_back(root->val);
bl(root->right, res, re, sum - root->val);
re.pop_back();
}
};