Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For 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 binary tree
* 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)
{
rslt.clear();
curList.clear();
if (!root)
{
return rslt;
}
DFS(root,0,sum);
return rslt;
}
private:
vector<vector<int >> rslt;
vector<int> curList;
void DFS(TreeNode * Node, int last, int sum)
{
int curSum = last + Node->val;
curList.push_back(Node->val);
if (!Node->left && !Node->right && curSum == sum)
{
rslt.push_back(curList);
}
if (Node->left)
{
DFS(Node->left, curSum, sum);
}
if (Node->right)
{
DFS(Node->right, curSum, sum);
}
curList.pop_back();
}
};
有更好的方式欢迎交流学习!