scala代码
/**
* @Description todo
* @Author Wang duzui
* @Date2020/7/24 20:05
**/
object BinaryTree {
def main(args: Array[String]): Unit = {
val arr: Array[String] = Array("5","1","9","8","7","2","4")
val tree = new BinaryTree(arr)
tree.preForeach(v=>print(v+" "))
println("----------")
tree.midForeach(v=>print(v+" "))
println("----------")
tree.afterForeach(v=>print(v+" "))
println("----------")
}
}
class BinaryTree[T:Ordering]() {
var root:Node[T] = _
def this(array: Array[T]) {
this
array.foreach(value => {
if (root == null) {
root = Node[T](value,null,null)
}else {
root.insert(value)
}
})
}
def preForeach(op:T => Unit): Unit = {
if(root !=null) root.preForeach(op)
}
def midForeach(op:T => Unit): Unit = {
if(root !=null) root.midForeach(op)
}
def afterForeach(op:T => Unit): Unit = {
if(root !=null) root.afterForeach(op)
}
}
case class Node[T:Ordering](var value:T,var left:Node[T],var right: Node[T]) {
def bigger(implicit ord:Ordering[T],x:T,y:T)= {
if (ord.compare(x, y) > 0) true else false
}
def insert(value :T ):Unit ={
if(!bigger(Ordering[T],value,this.value)){
if(left!=null){
left.insert(value)
}else{
left = Node[T](value,null,null)
}
}else{
if (right!=null){
right.insert(value)
}else{
right=Node[T](value,null,null)
}
}
}
def preForeach(op:T => Unit): Unit = {
op(value)
if(left!=null) left.preForeach(op)
if(right!=null) right.preForeach(op)
}
def midForeach(op:T => Unit): Unit = {
if(left!=null) left.midForeach(op)
op(value)
if(right!=null) right.midForeach(op)
}
def afterForeach(op:T => Unit): Unit = {
if(left!=null) left.afterForeach(op)
if(right!=null) right.afterForeach(op)
op(value)
}
}