排序二叉树,scala,先序,中序,后序遍历

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值