We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b1c2bdf commit 027cb6cCopy full SHA for 027cb6c
java/0606-construct-string-from-binary-tree.java
@@ -9,6 +9,25 @@ public String tree2str(TreeNode root) {
9
10
return output;
11
}
12
+}
13
+/* Alternative Solution
14
+-----------------------------------------------------------------*/
15
+class Solution {
16
+ public String tree2str(TreeNode root) {
17
+ StringBuilder res = new StringBuilder();
18
+ dfs(root, res);
19
+ return res.toString().substring(1, res.length()-1);
20
+ }
21
+ private void dfs(TreeNode root, StringBuilder res){
22
+ if(root == null)
23
+ return;
24
-
25
+ res.append("(");
26
+ res.append(root.val);
27
+ if(root.left == null && root.right != null)
28
+ res.append("()");
29
+ dfs(root.left, res);
30
+ dfs(root.right, res);
31
+ res.append(")");
32
33
0 commit comments