Skip to content

Commit faa0019

Browse files
committed
Time: 1 ms (100.00%), Space: 43.2 MB (81.65%) - LeetHub
1 parent 723b554 commit faa0019

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public String tree2str(TreeNode t) {
18+
StringBuilder res = new StringBuilder();
19+
dfs(t, res);
20+
return res.toString();
21+
}
22+
23+
public static void dfs(TreeNode t, StringBuilder res) {
24+
if (t == null)
25+
return;
26+
res.append(String.valueOf(t.val));
27+
if (t.left == null && t.right == null)
28+
return;
29+
res.append('(');
30+
dfs(t.left, res);
31+
res.append(')');
32+
if (t.right != null) {
33+
res.append('(');
34+
dfs(t.right, res);
35+
res.append(')');
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)