Construct String from Binary Tree LeetCode solution in Python

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('('); tree2str(root->left,s); s.push_back(')');
10

11
if(root->right){
12
s.push_back('('); tree2str(root->right,s); s.push_back(')');
13
}
14
}
15
public:
16
string tree2str(TreeNode* root) {
17
string ans = "";
18
tree2str(root,ans);
19
return ans;
20
}
21
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0