-
Notifications
You must be signed in to change notification settings - Fork 0
/
25_jianzhi_path.cpp
68 lines (60 loc) · 1.84 KB
/
25_jianzhi_path.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
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
vector<vector<int>> paths;
vector<int> path;
public:
/*vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int>> paths;
vector<int> path;
stack<TreeNode*> nodeS;
while(root || !nodeS.empty()){
while(root){
nodeS.push(root);
expectNumber = expectNumber - root->val;
path.push_back(root->val);
root = root->left? root->left : root->right;
}
root = nodeS.top();
if(root->left == NULL && root->right == NULL && expectNumber == 0){
paths.push_back(path);
}
expectNumber += root->val;
nodeS.pop();
path.pop_back();
if(!nodeS.empty() && nodeS.top()->left == root)
root = nodeS.top()->right;
else
root = NULL;
}
return paths;
}*/
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
dfsFindPath(root,expectNumber);
return paths;
}
void dfsFindPath(TreeNode* root,int expectNumber) {
//stack<TreeNode*> s;
if(root == NULL)
return;
path.push_back(root->val);
expectNumber -= root->val;
if(expectNumber == 0 && root->left == NULL && root->right == NULL)
paths.push_back(path);
else{
if(root->left)
dfsFindPath(root->left, expectNumber);
if(root->right)
dfsFindPath(root->right, expectNumber);
}
path.pop_back();
expectNumber += root->val;
}
};