-
Notifications
You must be signed in to change notification settings - Fork 0
/
0606-construct-string-from-binary-tree.kt
61 lines (49 loc) · 1.5 KB
/
0606-construct-string-from-binary-tree.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// recursion
class Solution {
fun tree2str(root: TreeNode?): String {
val res = StringBuilder()
fun preOrder(root: TreeNode?) {
root?: return
res.append("(")
res.append(root.`val`)
if (root.left == null && root.right != null)
res.append("()")
preOrder(root.left)
preOrder(root.right)
res.append(")")
}
preOrder(root)
res.deleteCharAt(0)
res.deleteCharAt(res.lastIndex)
return res.toString()
}
}
// iterative
class Solution {
fun tree2str(root: TreeNode?): String {
root?: return ""
val res = StringBuilder()
val stack = LinkedList<TreeNode?>().apply { addLast(root) }
val visited = HashSet<TreeNode?>()
while (stack.isNotEmpty()) {
val cur = stack.peekLast()
if (cur in visited) {
stack.removeLast()
res.append(")")
} else {
visited.add(cur)
res.append("(")
res.append(cur?.`val`)
if (cur?.left == null && cur?.right != null)
res.append("()")
if (cur?.right != null)
stack.addLast(cur?.right)
if (cur?.left != null)
stack.addLast(cur?.left)
}
}
res.deleteCharAt(0)
res.deleteCharAt(res.lastIndex)
return res.toString()
}
}