-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathConstructStringFromBinaryTree.cpp
More file actions
51 lines (42 loc) · 996 Bytes
/
Copy pathConstructStringFromBinaryTree.cpp
File metadata and controls
51 lines (42 loc) · 996 Bytes
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
/**
* 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 make(TreeNode* t, string& s){
if(!t){
return;
}
s = s + to_string(t->val);
if(!t->left && !t->right){
return;
}
s = s + "(";
if(!t->left && t->right){
s = s + ")(";
make(t->right, s);
s = s + ")";
return;
}
else if(t->left && !t->right){
make(t->left, s);
s = s + ")";
return;
}
make(t->left, s);
s = s + ")(";
make(t->right, s);
s = s + ")";
}
string tree2str(TreeNode* t) {
string ans = "";
make(t, ans);
return ans;
}
};