Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb1c2bdf

Browse files
authored
Update 0606-construct-string-from-binary-tree.kt
1 parentc08a096 commitb1c2bdf

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
classSolution {
23
funtree2str(root:TreeNode?):String {
34
val res=StringBuilder()
@@ -22,3 +23,39 @@ class Solution {
2223
return res.toString()
2324
}
2425
}
26+
27+
// iterative
28+
classSolution {
29+
funtree2str(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 (curin 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)

[8]ページ先頭

©2009-2025 Movatter.jp