Construct String from Binary Tree LeetCode solution in C++

1
class Solution {
2
void tree2str(TreeNode *root, string &s) {
3
if (!root) return;
4

5
s += to_string(root->val);
6

7
if (!root->left && !root->right) return;
8

9
s.push_back('(');
10
tree2str(root->left, s);
11
s.push_back(')');
12

13
if (root->right) {
14
s.push_back('(');
15
tree2str(root->right, s);
16
s.push_back(')');
17
}
18
}
19

20
public:
21
string tree2str(TreeNode *root) {
22
string ans = "";
23
tree2str(root, ans);
24
return ans;
25
}
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0