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 {
vector<vector<int>> result;
void pathsum(TreeNode *root,int cursum,int sum,vector<int> cur)
{
if(root==NULL) return ;
if(root->left==NULL && root->right==NULL)
{
if(cursum+root->val==sum)
{
cur.push_back(root->val);
result.push_back(cur);
}
return;
}
cursum+=root->val;
cur.push_back(root->val);
pathsum(root->left,cursum,sum,cur);
pathsum(root->right,cursum,sum,cur);
}
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<int> cur;
pathsum(root,0,sum,cur);
return result;
}
};