-
Notifications
You must be signed in to change notification settings - Fork 92
/
P56.kt
33 lines (28 loc) · 1.43 KB
/
P56.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package org.kotlin99.binarytrees
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.Test
import org.kotlin99.binarytrees.Tree.End
import org.kotlin99.binarytrees.Tree.Node
fun Tree<*>.isSymmetric(): Boolean = this == End || (this is Node<*> && left.isMirrorOf(right))
fun Tree<*>.isMirrorOf(that: Tree<*>): Boolean =
when {
this is Node<*> && that is Node<*> -> left.isMirrorOf(that.right) && right.isMirrorOf(that.left)
this == End -> that == End
else -> false
}
class P56Test {
@Test fun `tree is mirror of another tree`() {
assertThat(Node("x").isMirrorOf(Node("x")), equalTo(true))
assertThat(Node("x").isMirrorOf(Node("x", Node("x"))), equalTo(false))
assertThat(Node("x", End, Node("x")).isMirrorOf(Node("x", End, Node("x"))), equalTo(false))
assertThat(Node("x", End, Node("x")).isMirrorOf(Node("x", Node("x"))), equalTo(true))
}
@Test fun `tree is symmetric`() {
assertThat(Node("x").isSymmetric(), equalTo(true))
assertThat(Node("x", Node("x")).isSymmetric(), equalTo(false))
assertThat(Node("x", End, Node("x")).isSymmetric(), equalTo(false))
assertThat(Node("x", Node("x"), Node("x")).isSymmetric(), equalTo(true))
assertThat(Node("x", Node("x", End, Node("x")), Node("x", Node("x"))).isSymmetric(), equalTo(true))
}
}