-
Notifications
You must be signed in to change notification settings - Fork 0
/
200609-1.cpp
92 lines (86 loc) · 1.51 KB
/
200609-1.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// https://leetcode-cn.com/problems/binary-tree-paths/
#include <iostream>
#include <vector>
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) {
vector<string> a;
visit(root, a, "");
return a;
}
private:
void visit(TreeNode* t, vector<string>& a, string prefix) {
if (t) {
prefix += (prefix.empty() ? "" : "->") + to_string(t->val);
if (!t->left && !t->right) {
a.push_back(prefix);
} else {
if (t->left) {
visit(t->left, a, prefix);
}
if (t->right) {
visit(t->right, a, prefix);
}
}
}
}
};
void print(TreeNode* t, bool endl = true)
{
if (t) {
cout << "(" << t->val;
if (t->left || t->right) {
cout << ", ";
if (t->left) {
print(t->left, false);
} else {
cout << "null";
}
cout << ", ";
if (t->right) {
print(t->right, false);
} else {
cout << "null";
}
}
cout << ")";
if (endl) cout << std::endl;
}
}
void release(TreeNode* t)
{
if (t) {
release(t->left);
release(t->right);
delete t;
}
}
void print(const vector<string>& a)
{
cout << "[ ";
for (const auto& s : a) {
cout << "\"" << s << "\" ";
}
cout << "]" << endl;
}
int main()
{
Solution s;
{
TreeNode* t = new TreeNode(1);
t->left = new TreeNode(2);
t->right = new TreeNode(3);
t->left->right = new TreeNode(5);
print(s.binaryTreePaths(t));
print(t);
release(t);
}
return 0;
}