impl visit tree
This commit is contained in:
parent
b9749985c0
commit
e636bfaa9b
39
scala/src/main/scala/ch23_binary_tree/BinaryTree.scala
Normal file
39
scala/src/main/scala/ch23_binary_tree/BinaryTree.scala
Normal 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
|
||||
}
|
||||
}
|
48
scala/src/test/scala/ch23_binary_tree/BinaryTreeTest.scala
Normal file
48
scala/src/test/scala/ch23_binary_tree/BinaryTreeTest.scala
Normal 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")
|
||||
}
|
||||
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user