【leetcode】Path Sum II

时间:2022-04-08 10:13:45

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.

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