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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
object bTreeExample {
abstract class BinaryTree
case class Node(value: Int, left: BinaryTree = null, right: BinaryTree = null) extends BinaryTree
def traverse(t: BinaryTree): Unit = { t match { case null => Unit case Node(v, left, right) => traverse(left);println(v);traverse(right) } }
def BFS(t: (List[Node], List[Int])): (List[Node], List[Int]) = t match { case (Nil, res) => (Nil, res) case (lB, res) => { val tmp = lB.map { case Node(v, null, null) => (Nil, v) case Node(v, left, null) => (List(left.asInstanceOf[Node]), v) case Node(v, null, right) => (List(right.asInstanceOf[Node]), v) case Node(v, left, right) => (List(left.asInstanceOf[Node], right.asInstanceOf[Node]), v) } BFS((tmp.flatMap(_._1), res ++ tmp.map(_._2))) } }
def DFS(t:(List[Node], List[Int])): (List[Node], List[Int]) =t match{ case (Nil, res) => (Nil, res) case (lB, res) => { val top = lB.head val left = if(top.left == null) Nil else List(top.left.asInstanceOf[Node]) val right = if(top.right == null) Nil else List(top.right.asInstanceOf[Node]) DFS(left ++ right ++ lB.tail, res ++ List(top.value)) } }
def main(args: Array[String]): Unit = { val t = Node(1, Node(2, Node(4), Node(5, Node(7), Node(8))), Node(3, null, Node(6))) val res = DFS((List(t), List.empty[Int])) println(res._2)
}
}
|
Gitalking ...