-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path SumII.cpp
69 lines (65 loc) · 1.72 KB
/
Path SumII.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
void cur(vector<vector<int> >& re,vector<int>& cur_re,TreeNode* t,int sum,int tsum)
{
if (t->left==NULL&&t->right==NULL)
{
if (tsum==sum)
{
re.push_back(cur_re);
return;
}
else
return;
}
if (t->left!=NULL)
{
cur_re.push_back(t->left->val);
cur(re,cur_re,t->left,sum,tsum+t->left->val);
cur_re.pop_back();
}
if (t->right!=NULL)
{
cur_re.push_back(t->right->val);
cur(re,cur_re,t->right,sum,tsum+t->right->val);
cur_re.pop_back();
}
}
vector<vector<int> > pathSum(TreeNode* root, int sum) {
vector<vector<int> > re;
vector<int> cur_re;
if (root==NULL)
return re;
cur_re.push_back(root->val);
cur(re,cur_re,root,sum,root->val);
return re;
}
int main()
{
TreeNode* root=new TreeNode(5);
root->left=new TreeNode(4);
root->right=new TreeNode(8);
root->left->left=new TreeNode(11);
root->right->left=new TreeNode(13);
root->right->right=new TreeNode(4);
root->left->left->left=new TreeNode(7);
root->left->left->right=new TreeNode(2);
root->right->right->left=new TreeNode(5);
root->right->right->right=new TreeNode(1);
vector<vector<int> > re;
re=pathSum(root,22);
for (int i=0;i<re.size();i++)
{
for (int j=0;j<re[i].size();j++)
cout<<re[i][j]<<" ";
cout<<endl;
}
return 0;
}