スケイラですみません(◞‸◟) もちがってる可能性があります。
def suffixes[A](xs: List[A]): List[List[A]] = xs match {
case Nil => List(Nil)
case _ :: tail => xs :: suffixes(tail)
}
def member22(x: Int, tree: BinarySearchTree): Boolean = member22(x, tree, None)
@annotation.tailrec
private def member22(x: Int, tree: BinarySearchTree, candidate: Option[Int]): Boolean = {
tree match {
case Node(left, y, _) if x < y => member22(x, left, candidate)
case Node(_, y, right) if x >= y => member22(x, right, Some(y))
case Empty =>
candidate match {
case Some(`x`) => true
case _ => false
}
}
}
def insert23(x: Int, tree: BinarySearchTree): BinarySearchTree = try {
insert23OrError(x, tree)
} catch {
case e: RuntimeException => tree
}
private def insert23OrError(x: Int, tree: BinarySearchTree): BinarySearchTree = tree match {
case Node(left, y, right) if x < y => Node(insert(x, left), y, right)
case Node(left, y, right) if x > y => Node(left, y, insert(x, right))
case Node(_, `x`, _) => throw new RuntimeException("already exists.")
case Empty => Node(Empty, x, Empty)
}
def insert24(x: Int, tree: BinarySearchTree): BinarySearchTree = try {
insert24OrError(x, tree, None)
} catch {
case e: RuntimeException => tree
}
private def insert24OrError(x: Int, tree: BinarySearchTree, candidate: Option[Int]): BinarySearchTree = {
tree match {
case Node(left, y, right) if x < y => Node(insert24OrError(x, left, candidate), y, right)
case Node(left, y, right) => Node(left, y, insert24OrError(x, right, Some(y)))
case Empty => candidate match {
case Some(`x`) => throw new RuntimeException("already exists.")
case _ => Node(Empty, x, Empty)
}
}
}
sealed abstract class BinaryTree
case object Empty extends BinaryTree
case class Node(left: BinaryTree, elem: Int, right: BinaryTree) extends BinaryTree
object BinaryTree {
def complete(x: Int, depth: Int): BinaryTree = depth match {
case 0 => Empty
case n =>
val subTree = complete(x, depth - 1)
Node(subTree, x, subTree)
}
}
def create(x: Int, size: Int): BinaryTree = size match {
case 0 => Empty
case 1 => Node(Empty, x, Empty)
case n if n % 2 == 0 =>
val (left, right) = create2(x, (n - 1) / 2)
Node(left, x, right)
case n =>
val subTree = create(x, (n - 1) / 2)
Node(subTree, x, subTree)
}
private def create2(x: Int, size: Int): (BinaryTree, BinaryTree) = {
(create(x, size), create(x, size + 1))
}
- TreeMapにすればいい
- NodeはKey-Valueペアを持つ
- 木はKeyのOrderingを持つ