73 lines
1.9 KiB
Kotlin
73 lines
1.9 KiB
Kotlin
|
package net.shadowfacts.cacao.util
|
|||
|
|
|||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
|||
|
import org.junit.jupiter.api.Assertions.assertNull
|
|||
|
import org.junit.jupiter.api.Test
|
|||
|
|
|||
|
/**
|
|||
|
* @author shadowfacts
|
|||
|
*/
|
|||
|
class LCATest {
|
|||
|
|
|||
|
class Node(val name: String, val parent: Node?)
|
|||
|
|
|||
|
@Test
|
|||
|
fun testDirectParent() {
|
|||
|
val parent = Node("parent", null)
|
|||
|
val child = Node("child", parent)
|
|||
|
assertEquals(parent, LowestCommonAncestor.find(parent, child, Node::parent))
|
|||
|
assertEquals(parent, LowestCommonAncestor.find(child, parent, Node::parent))
|
|||
|
}
|
|||
|
|
|||
|
@Test
|
|||
|
fun testSiblings() {
|
|||
|
val root = Node("root", null)
|
|||
|
val a = Node("a", root)
|
|||
|
val b = Node("b", root)
|
|||
|
assertEquals(root, LowestCommonAncestor.find(a, b, Node::parent))
|
|||
|
}
|
|||
|
|
|||
|
@Test
|
|||
|
fun testBetweenSubtrees() {
|
|||
|
// ┌────┐
|
|||
|
// │root│
|
|||
|
// └────┘
|
|||
|
// ╱ ╲
|
|||
|
// ╱ ╲
|
|||
|
// ┌─┐ ┌─┐
|
|||
|
// │A│ │B│
|
|||
|
// └─┘ └─┘
|
|||
|
// ╱ ╲ ╱ ╲
|
|||
|
// ╱ ╲ ╱ ╲
|
|||
|
// ┌─┐ ┌─┐┌─┐ ┌─┐
|
|||
|
// │C│ │D││E│ │F│
|
|||
|
// └─┘ └─┘└─┘ └─┘
|
|||
|
val root = Node("root", null)
|
|||
|
|
|||
|
val a = Node("a", root)
|
|||
|
val c = Node("c", a)
|
|||
|
val d = Node("d", a)
|
|||
|
|
|||
|
val b = Node("b", root)
|
|||
|
val e = Node("e", b)
|
|||
|
val f = Node("f", b)
|
|||
|
|
|||
|
assertEquals(a, LowestCommonAncestor.find(c, d, Node::parent))
|
|||
|
assertEquals(root, LowestCommonAncestor.find(c, b, Node::parent))
|
|||
|
assertEquals(root, LowestCommonAncestor.find(d, e, Node::parent))
|
|||
|
assertEquals(root, LowestCommonAncestor.find(c, root, Node::parent))
|
|||
|
}
|
|||
|
|
|||
|
@Test
|
|||
|
fun testBetweenDisjointTrees() {
|
|||
|
val a = Node("a", null)
|
|||
|
val b = Node("b", a)
|
|||
|
|
|||
|
val c = Node("c", null)
|
|||
|
val d = Node("d", c)
|
|||
|
|
|||
|
assertNull(LowestCommonAncestor.find(a, d, Node::parent))
|
|||
|
assertNull(LowestCommonAncestor.find(b, c, Node::parent))
|
|||
|
}
|
|||
|
|
|||
|
}
|