10-顺序二叉树-Scala实现

用树的结构遍历数组

package com.atguigu.datastructures.binarytree

object ArrayTreeDemo {
  def main(args: Array[String]): Unit = {
    val arr = Array(1,2,3,4,5,6,7)
    val arrayTree = new ArrayTree(arr)
    arrayTree.postOrder()
  }
}
class ArrayTree(val arr:Array[Int]){
  //重载
  def preOrder(): Unit ={
    this.preOrder(0)

  }
  def infixOrder(): Unit ={
    this.infixOrder(0)
  }
  def postOrder(): Unit ={
    this.postOrder(0)
  }

  def preOrder(index:Int): Unit ={
    if (arr == null || arr.length == 0){
      println("数组为空,不能按照二叉树前序遍历")
    }
    println(arr(index))
    //向左递归遍历
    if ((index*2 + 1) < arr.length){
      preOrder(index*2 + 1)
    }
    //向右递归遍历
    if ((index*2 + 2) < arr.length){
      preOrder(index*2 + 2)
    }
  }

  def infixOrder(index:Int): Unit ={
    if (arr == null || arr.length == 0){
      println("数组为空,不能按照二叉树前序遍历")
    }
    //向左递归遍历
    if ((index*2 + 1) < arr.length){
      infixOrder(index*2 + 1)
    }
    println(arr(index))
    //向右递归遍历
    if ((index*2 + 2) < arr.length){
      infixOrder(index*2 + 2)
    }
  }
  def postOrder(index:Int): Unit ={
    if (arr == null || arr.length == 0){
      println("数组为空,不能按照二叉树前序遍历")
    }
    //向左递归遍历
    if ((index*2 + 1) < arr.length){
      postOrder(index*2 + 1)
    }
    //向右递归遍历
    if ((index*2 + 2) < arr.length){
      postOrder(index*2 + 2)
    }
    println(arr(index))
  }
}

  

posted @ 2020-07-13 10:26  济默  阅读(160)  评论(0编辑  收藏  举报