Last active
June 9, 2018 19:58
-
-
Save thomasnield/d795227d1b31299661359841ca2af2f2 to your computer and use it in GitHub Desktop.
Traversing a Binary Tree (Using a heuristic)
This file contains hidden or 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
| // PROBLEM VISUALIZATION (https://i.imgur.com/cwg5LZ9.png) | |
| val treeRowCount = 5 | |
| enum class Direction { | |
| ROOT, | |
| LEFT, | |
| RIGHT; | |
| } | |
| data class Node(val row: Int, | |
| val appliedDirection: Direction, | |
| val parent: Node? = null) { | |
| override fun toString() = generateSequence(this) { it.parent } | |
| .sortedBy { it.row } | |
| .map { "(row=${it.row},dir=${it.appliedDirection})" } | |
| .joinToString(" -> ") | |
| } | |
| fun traverse(node: Node, rightMovesLeft: Int) { | |
| var nextNode = node | |
| for (i in (node.row+1) until treeRowCount) { | |
| if (rightMovesLeft > 0) | |
| traverse(Node(i, Direction.RIGHT,nextNode), rightMovesLeft - 1) | |
| nextNode = Node(i,Direction.LEFT, nextNode) | |
| } | |
| println(nextNode) | |
| } | |
| fun main(args: Array<String>) { | |
| for (wave in 0..(treeRowCount-1)) { | |
| println("WAVE: $wave") | |
| traverse(Node(0,Direction.ROOT), wave) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment