Skip to content

Commit 24a1ade

Browse files
committed
#606. Construct String from Binary Tree (C++) - 55ms/24.24% 53.4MB/41.81%
1 parent 57bdced commit 24a1ade

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//#606. Construct String from Binary Tree (C++) - 55ms/24.24% 53.4MB/41.81%
2+
/**
3+
* Definition for a binary tree node.
4+
* struct TreeNode {
5+
* int val;
6+
* TreeNode *left;
7+
* TreeNode *right;
8+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
10+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
string tree2str(TreeNode* root) {
16+
if (root == nullptr) return "";
17+
else {
18+
string out;
19+
out.append(to_string(root->val));
20+
string left = tree2str(root->left);
21+
string right = tree2str(root->right);
22+
if (left != "" || right != "") {
23+
out.push_back('(');
24+
out.append(left);
25+
out.push_back(')');
26+
}
27+
if (right != "") {
28+
out.push_back('(');
29+
out.append(right);
30+
out.push_back(')');
31+
}
32+
return out;
33+
}
34+
}
35+
};

0 commit comments

Comments
 (0)