impl visit tree

This commit is contained in:
Ivan Li 2019-01-07 20:58:20 +08:00
parent b9749985c0
commit e636bfaa9b
2 changed files with 87 additions and 0 deletions

View File

@ -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
}
}

View File

@ -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")
}
}