Skip to content

Commit b1c2bdf

Browse files
authored
Update 0606-construct-string-from-binary-tree.kt
1 parent c08a096 commit b1c2bdf

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

kotlin/0606-construct-string-from-binary-tree.kt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// recursion
12
class Solution {
23
fun tree2str(root: TreeNode?): String {
34
val res = StringBuilder()
@@ -22,3 +23,39 @@ class Solution {
2223
return res.toString()
2324
}
2425
}
26+
27+
// iterative
28+
class Solution {
29+
fun tree2str(root: TreeNode?): String {
30+
root?: return ""
31+
32+
val res = StringBuilder()
33+
val stack = LinkedList<TreeNode?>().apply { addLast(root) }
34+
val visited = HashSet<TreeNode?>()
35+
36+
while (stack.isNotEmpty()) {
37+
val cur = stack.peekLast()
38+
39+
if (cur in visited) {
40+
stack.removeLast()
41+
res.append(")")
42+
} else {
43+
visited.add(cur)
44+
res.append("(")
45+
res.append(cur?.`val`)
46+
47+
if (cur?.left == null && cur?.right != null)
48+
res.append("()")
49+
50+
if (cur?.right != null)
51+
stack.addLast(cur?.right)
52+
if (cur?.left != null)
53+
stack.addLast(cur?.left)
54+
}
55+
}
56+
57+
res.deleteCharAt(0)
58+
res.deleteCharAt(res.lastIndex)
59+
return res.toString()
60+
}
61+
}

0 commit comments

Comments
 (0)