-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: 💡 extract tree traversal methods to new class
- Loading branch information
1 parent
7494945
commit ae03634
Showing
2 changed files
with
52 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
core/src/main/kotlin/tw/xcc/gumtree/model/TraversalHelper.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package tw.xcc.gumtree.model | ||
|
||
import tw.xcc.gumtree.api.tree.Traversable | ||
import tw.xcc.gumtree.api.tree.Tree | ||
|
||
class TraversalHelper<T>( | ||
private val tree: T | ||
) : Traversable<T> where T : Tree<T>, T : Any { | ||
private fun preOrderedImpl( | ||
tree: T, | ||
visited: MutableSet<T> | ||
) { | ||
visited.add(tree) | ||
tree.children.forEach { | ||
preOrderedImpl(it, visited) | ||
} | ||
} | ||
|
||
private fun postOrderedImpl( | ||
tree: T, | ||
visited: MutableSet<T> | ||
) { | ||
tree.children.forEach { | ||
postOrderedImpl(it, visited) | ||
} | ||
visited.add(tree) | ||
} | ||
|
||
override fun preOrdered(): List<T> { | ||
synchronized(tree) { | ||
val visited = mutableSetOf<T>() | ||
preOrderedImpl(tree, visited) | ||
return visited.toList() | ||
} | ||
} | ||
|
||
override fun postOrdered(): List<T> { | ||
synchronized(tree) { | ||
val visited = mutableSetOf<T>() | ||
postOrderedImpl(tree, visited) | ||
return visited.toList() | ||
} | ||
} | ||
} |