-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path113.cpp
More file actions
49 lines (47 loc) · 1.22 KB
/
Copy path113.cpp
File metadata and controls
49 lines (47 loc) · 1.22 KB
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
#include <vector>
#include <iostream>
using std::vector;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/* 16 ms 69.96%
* 20 MB 50.00%
*/
class Solution {
public:
vector<vector<int>> res;
int sum;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> stack;
this->sum = sum;
order(root, stack, 0);
return res;
}
void order(TreeNode* root, vector<int>& stack,int sum) {
if (root != nullptr) {
stack.push_back(root->val);
sum += root->val;
if (root->left || root->right) { // 是否是根节点
order(root->left, stack, sum);
order(root->right, stack, sum);
} else {
if (sum == this->sum) {
this->res.push_back(stack); // push_back为拷贝操作
}
}
stack.pop_back();
}
}
};