-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path606.cpp
70 lines (64 loc) · 1.82 KB
/
606.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
__________________________________________________________________________________________________
sample 16 ms submission
/**
* 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:
string tree2str(TreeNode* t) {
ostringstream s;
rec(t, s);
return s.str();
}
void rec(TreeNode *t, ostringstream &s) {
if (!t) return;
s << t->val;
if (!t->left && !t->right) return;
s << '(';
rec(t->left, s);
s << ')';
if (t->right) {
s << '(';
rec(t->right, s);
s << ')';
}
}
};
static int _ = []{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);return 0;}();
__________________________________________________________________________________________________
sample 20868 kb submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
const static int _FAST_IO = [](){ios::sync_with_stdio(0); std::cin.tie(0); return 0;}();
class Solution {
public:
std::string tree2str(const TreeNode *t) const {
std::ostringstream stream;
dfs(stream, t);
return stream.str();
}
void dfs(ostringstream &stream, const TreeNode *t) const {
if (!t) return;
stream << t->val;
if (t->left || t->right) {
stream << "("; dfs(stream, t->left); stream << ")";
}
if (t->right) {
stream << "("; dfs(stream, t->right); stream << ")";
}
}
};
__________________________________________________________________________________________________