diff --git a/scala/src/main/scala/ch23_binary_tree/BinaryTree.scala b/scala/src/main/scala/ch23_binary_tree/BinaryTree.scala new file mode 100644 index 0000000..efc6bce --- /dev/null +++ b/scala/src/main/scala/ch23_binary_tree/BinaryTree.scala @@ -0,0 +1,39 @@ +package ch23_binary_tree + +class Node[T](var data: T, var left: Option[Node[T]], var right: Option[Node[T]]) + +class BinaryTree[T] { + + def preOrder(root: Option[Node[T]]): String = { + val result = new StringBuilder + + if (root.isDefined) { + result.append(root.map(_.data.toString).get) + result.append(preOrder(root.get.left)) + result.append(preOrder(root.get.right)) + } + result.mkString + } + + def inOrder(root: Option[Node[T]]): String = { + val result = new StringBuilder + + if (root.isDefined) { + result.append(inOrder(root.get.left)) + result.append(root.map(_.data.toString).get) + result.append(inOrder(root.get.right)) + } + result.mkString + } + + def postOrder(root: Option[Node[T]]): String = { + val result = new StringBuilder + + if (root.isDefined) { + result.append(postOrder(root.get.left)) + result.append(postOrder(root.get.right)) + result.append(root.map(_.data.toString).get) + } + result.mkString + } +} diff --git a/scala/src/test/scala/ch23_binary_tree/BinaryTreeTest.scala b/scala/src/test/scala/ch23_binary_tree/BinaryTreeTest.scala new file mode 100644 index 0000000..2ee3f95 --- /dev/null +++ b/scala/src/test/scala/ch23_binary_tree/BinaryTreeTest.scala @@ -0,0 +1,48 @@ +package ch23_binary_tree + +import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers} + +class BinaryTreeTest extends FlatSpec with BeforeAndAfterEach with Matchers { + + /* + * A + * / \ + * B C + * / \ / \ + * D E F G + * + */ + var root:Option[Node[String]] = None + val tree = new BinaryTree[String] + + override def beforeEach() { + val D = new Node[String]("D", None, None) + val E = new Node[String]("E", None, None) + val B = new Node[String]("B", Some(D), Some(E)) + val F = new Node[String]("F", None, None) + val G = new Node[String]("G", None, None) + val C = new Node[String]("C", Some(F), Some(G)) + val A = new Node[String]("A", Some(B), Some(C)) + root = Some(A) + } + + override protected def afterEach(): Unit = { + root = None + } + + behavior of "BinaryTreeTest" + + it should "postOrder" in { + tree.postOrder(root) should equal("DEBFGCA") + } + + it should "inOrder" in { + tree.inOrder(root) should equal("DBEAFCG") + } + + it should "preOrder" in { + tree.preOrder(root) should equal("ABDECFG") + } + + +}