Skip to content

Commit ebb5d9a

Browse files
committed
package com.github.masx200.leetcode_test.binary_search_tree_iterator
1 parent 0d466f0 commit ebb5d9a

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

binary-search-tree-iterator/index.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.github.masx200.leetcode_test.binary_search_tree_iterator
2+
3+
import com.github.masx200.leetcode_test.insert_into_a_binary_search_tree.TreeNode
4+
5+
class BSTIterator(root: TreeNode?) {
6+
private val generator = InOrderIterator(root).iterator()
7+
fun next(): Int {
8+
return this.generator.next()
9+
}
10+
11+
fun hasNext(): Boolean {
12+
return this.generator.hasNext()
13+
}
14+
15+
}
16+
17+
fun InOrderIterator(root: TreeNode?): Sequence<Int> {
18+
return sequence {
19+
20+
if (root == null) return@sequence
21+
22+
yieldAll(InOrderIterator(root.left))
23+
yield(root.`val`)
24+
yieldAll(InOrderIterator(root.right))
25+
}
26+
}
27+

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
</goals>
8787
<configuration>
8888
<sourceDirs>
89+
<sourceDir>binary-search-tree-iterator</sourceDir>
8990
<sourceDir>construct-binary-search-tree-from-preorder-traversal</sourceDir>
9091
<source>er-cha-shu-ran-se-UGC</source>
9192
<source>er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof</source>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.github.masx200.leetcode_test.binary_search_tree_iterator
2+
3+
import com.github.masx200.leetcode_test.utils.TreeNodeLeetCodeParse
4+
import org.junit.jupiter.api.Test
5+
import kotlin.test.assertContentEquals
6+
7+
internal class BSTIteratorTest {
8+
9+
@Test
10+
fun testnext() {
11+
val iterator = BSTIterator(TreeNodeLeetCodeParse("[7, 3, 15, null, null, 9, 20]"))
12+
13+
val res = mutableListOf<Int>()
14+
while (iterator.hasNext()) {
15+
res.add(iterator.next())
16+
}
17+
assertContentEquals(res, listOf(3, 7, 9, 15, 20))
18+
19+
}
20+
}

0 commit comments

Comments
 (0)