-
Notifications
You must be signed in to change notification settings - Fork 119
/
257.cpp
60 lines (46 loc) · 1.13 KB
/
257.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
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<string> binaryTreePaths(TreeNode *root) {
string path = "";
vector<string> ans;
dfs(root, ans, path);
return ans;
}
void dfs(TreeNode *root, vector<string> &ans, string path) {
if (root == NULL) {
return;
}
path += to_string(root->val);
if (root->left == NULL && root->right == NULL) {
ans.push_back(path);
return;
}
path += "->";
dfs(root->left, ans, path);
dfs(root->right, ans, path);
}
};
int main() {
TreeNode *r = new TreeNode(1);
r->left = new TreeNode(2);
r->right = new TreeNode(3);
r->left->left = NULL;
r->left->right = new TreeNode(5);
Solution s;
vector<string> paths = s.binaryTreePaths(r);
for (int i = 0; i < paths.size(); i++) {
cout << paths[i] << endl;
}
return 0;
}