Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 027cb6c

Browse files
Update 0606-construct-string-from-binary-tree.java
1 parent b1c2bdf commit 027cb6c

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

java/0606-construct-string-from-binary-tree.java

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,25 @@ public String tree2str(TreeNode root) {
99

1010
return output;
1111
}
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;
1224

13-
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+
}
1433
}

0 commit comments

Comments
 (0)