-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathbinary-tree-paths.cpp
42 lines (39 loc) · 1.08 KB
/
binary-tree-paths.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void buildPaths(TreeNode* root, vector<string>& res, vector<string>& path) {
if (root == NULL) {
return;
}
if (path.empty()) {
path.push_back(to_string(root->val));
} else {
path.push_back("->" + to_string(root->val));
}
if (root->left == NULL && root->right == NULL) {
string target("");
for (int i = 0; i < path.size(); ++i) {
target += path[i];
}
res.push_back(target);
} else {
if (root->left) buildPaths(root->left, res, path);
if (root->right) buildPaths(root->right, res, path);
}
path.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
vector<string> path;
buildPaths(root, res, path);
return res;
}
};